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:
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.
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&)).
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