C++: Function overload preferences

The function overload rules in C++ are sometimes surprising. Herb Sutter wrote an excellent Guru of the Week article on function overload rules some time ago, but here’s some code to differentiate between some of the common overloads:

#include <iostream>
#include <string>

template<typename T>
void foo(T t)
{
    std::cout << "Generic Template function: " << t << "\n";
}

template<>
void foo<int>(int i)
{
    std::cout << "Function template specialization for int: " << i << "\n";
}

template<>
void foo<bool>(bool b)
{
    std::cout << "Function template specialization for bool: " << b << "\n";
}

void foo( double d )
{
    std::cout << "Non-template overload for double: " << d << "\n";
}

void foo( int i )
{
    std::cout << "Non-template overload for int: " << i << "\n";
}

int main()
{
    std::string s = "Hello, World";
    foo(s); // Calls generic template

    bool b = true;
    foo(b); // Calls template specialization

    double d = 1.0;
    foo(d); // Exact match to non-template overload

    int i = 0;
    foo(i); // Exact match (better than template specialization)

    short sh = 255;
    foo(sh); // Not exact match, calls generic template

    return 0;
}

FunctionOverloadOutput

Leave a comment

Filed under C++, C++ Code, Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.