I have a piece of code similar to this:
#include <iostream>
using namespace std;
template<typename T>
class Class
{
public:
Class() {}
void foo(T) {cout << "foo(T) is called \n";}
void foo(T&) {cout << "foo(T&) is called \n";}
};
int main()
{
Class<int> c;
int a = 1;
c.foo(1);
c.foo(a);
return 0;
}
I want to have both overloads of function foo
because foo(T&)
is more efficient but I can't use a literal constant as it's argument and foo(T)
will work for literal constants although it is not as efficient as foo(T&)
. But when I define both functions there will be an ambiguous call when c.foo(a)
is going to execute.
error: call of overloaded 'foo(int&)' is ambiguous
How can I overcome this problem?
You can pass by const reference const T&
so that it will also accept literal constants, or pass by rvalue reference T&&
instead of T
so that it will only accept rvalues (like literal constants)