Reputation: 2671
Running the following code snippet, I do not receive any errors and I get my expected result. However, since the second template instantiation is ambiguous (both type specifiers are references), I am worried that this might not be defined behavior.
Is this behavior (that the compiler instantiates the most specific overloaded template) guaranteed?
#include <algorithm>
#include <iostream>
#include <vector>
template<typename T>
void Print(const T& x)
{
std::cout << x << std::endl;
}
template<typename T>
void Print(const std::vector<T>& x)
{
for(auto it = x.begin(); it != x.end(); ++it)
{
std::cout << *it << " ";
}
std::cout << std::endl;
}
int main(int argc, char const *argv[])
{
std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Print(5); // 5
Print(v); // 0 1 2 3 4 5 6 7 8 9
return 0;
}
I am not sure where to look so a good reference is also greatly appreciated.
Upvotes: 0
Views: 91
Reputation: 206567
const std::vector<T>& x
is a more specialized type than const T& x
. A more specialized type is considered a better match for overload resolution. Hence, your code behaves like it should.
Upvotes: 4