I have overloaded methods:
template<typename AnyType>
void AnyFunc(AnyType &t);
template<typename AnyType>
void AnyFunc(AnyType &&t);
I have a caller which holds a pointer and want to use one of the functions:
MyType* ptr=new MyType();
AnyFunc(*ptr);
The last line runs into compile error: ambiguous overload for AnyFunc
How can I select the function I need? The simple case is to use:
AnyFunc(std::move(*ptr));
which select the void AnyFunc(AnyType &&t); but this is not what I want. I need the
void AnyFunc(AnyType &t); method.
Any time you have
T&& v(whereTis a template parameter), you have a so-called universal reference. Not only does it bind to rvalues, but also to lvalues. It’s a greedy template. It will take anything it can get and give nothing back.Overloading when a greedy template is involved is a bad idea, unless you know exactly what you’re doing.
With universal references, there’s often no need to special-case lvalues vs rvalues. Just
std::forward<T>(v)the parameter and the value category will be propagated.