Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More specific overload not called

Tags:

c++

Given the following two functions, I would expect the first overload to be called if I pass it an std::pair<const char*, std::size_t>, since it is more specific than a generic T.

void foo(const std::pair<const char*, std::size_t>& p)
{
    std::cout << "pair" << std::endl;
}

template <class T>
void foo(const T& v)
{
    std::cout << "generic" << std::endl;
}

int main()
{
    const char* s = "abc";
    foo(std::make_pair(s, std::size_t(3)));
}

However, this program outputs:

generic

Why is the second overload called, instead of the overload that explicitly takes a pair?

Is this a compiler issue? I happen to be using a pretty old compiler (GCC 4.1.2) at the moment.

Hmm... it probably IS a compiler issue:

http://ideone.com/97XwwZ

like image 453
Channel72 Avatar asked Aug 08 '13 18:08

Channel72


People also ask

When an overloaded function is called?

In Java, function overloading is also known as compile-time polymorphism and static polymorphism.

How many types of overloading are there?

There are mainly two types of overloading, i.e. function overloading and operator overloading.

What are the different ways to overload a method?

Overloading MethodsBy changing the number of parameters in a method. By changing the order of parameters in a method. By using different data types for parameters.

Do all overloaded methods share the same name?

Method overloading happens with methods with the same name but different signature. Method overriding happens with methods with the same name and same signature between inherited classes. The return type can cause the same problem we saw above.


1 Answers

Your compiler is certainly in error. What error it is, will only be speculation, but you are correct that this code should give the more specific output. The sample isn't big or complex enough for any of the more subtle rules to be the cause.

like image 81
Puppy Avatar answered Oct 19 '22 13:10

Puppy