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
In Java, function overloading is also known as compile-time polymorphism and static polymorphism.
There are mainly two types of overloading, i.e. function overloading and operator overloading.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With