when I have both of these signatures, I get a compile error:
String& operator+(String&& a, const TCHAR* b)
String operator+(String a, const TCHAR* b)
string.cpp(97): error C2593: 'operator +' is ambiguous
string.cpp(34): could be 'String &operator +(String &&,const TCHAR *)'
string.cpp(24): or 'String operator +(String,const TCHAR *)'
Aren’t they different????? I feel like performance could be increased if I could use both. On the other hand, is this ambiguous because the + operator always deals with rvalues?
vc++ 2010 compiler
The problem is that those are different signatures, but all arguments that can be used with one can also be used with the other, so the compiler cannot possibly disambiguate what function needs to be called depending on the arguments.
You probably meant to provide two overloads that take an rvalue-reference and and lvalue-reference respectively. Also note that it probably makes no sense to return a reference from the first overload.
Note that using an rvalue and lvalue reference overloads is only needed if you really need to distinguish between the two use cases, but the general definition of
operator+does not require that distinction, as it does not modify the arguments. The common way of implementingoperator+is:Performance can be improved a bit to allow for moves on either the first or the second arguments to
operator+, but that requires 4 different combinations of lvalue/*rvalue* in both positions (lvalue+*lvalue; lvalue+*rvalue*; rvalue+*lvalue*; rvalue+*rvalue*)