Reputation: 13278
Consider this code:
#include <iostream>
void func(int&)
{
std::cout << "mutable" << std::endl;
}
void func(const int&)
{
std::cout << "const" << std::endl;
}
template<typename T>
void tpl_func(T&)
{
std::cout << "mutable_tpl" << std::endl;
}
template<typename T>
void tpl_func(const T&)
{
std::cout << "const_tpl" << std::endl;
}
class number
{
public:
operator int&()
{
return nb_;
}
operator const int&()
{
return nb_;
}
private:
int nb_ = 42;
};
int main()
{
number n;
func(n); // This produces: error: call to 'func' is ambiguous
tpl_func(n); // This compiles fine
}
Tested with clang3.5
Questions:
Upvotes: 3
Views: 127
Reputation: 217075
func(n);
requires a conversion, both func
are viable and overload is ambiguous.
tpl_func(n);
has an exact match (template<typename T> void tpl_func(T&)
).
Upvotes: 1
Reputation: 4283
Because in func(n)
there's an implicit function call (the int-conversion operator) which is ambiguous (you could choose any of the two) and in tpl_func(n)
you're NOT int-converting, i.e. the template deduces to tpl_func<number>(number &)
since n
is lvalue.
Upvotes: 3