Why is this rvalue call ambiguous?

Why is this rvalue call ambiguous? I can have AA and AA & and the compiler will know what to use AA& . But when I add to the third option, I get an error message. Obviously, AA && is a better overload, then others like int for int are better than long ones. Why is this ambiguous? Is there a way to save all 3 overloads and make it clear which one I want? (Typecasting (AA&&) will not do this).

 struct AA{ void*this_; AA() { this_=this; } //not valid, use AA&, AA(AA a){ this_=this; } AA(AA&a){ this_=this; } AA(AA&&a){ this_=a.this_; } }; void movetest(AA s) {} void movetest(AA& s) {} //This gets me the ambiguous error void movetest(AA&& s) {} AA&& movetest() { return AA(); } void MyTestCode2(){ AA a; AA b(a); AA c = movetest(); movetest(AA()); } 
+6
source share
2 answers

I can have AA and AA & and the compiler will know to use AA &

Yes, in the case of movetest (AA ()) , only movetest (AA) is viable, since a reference (lvalue) to a non-constant cannot be tied to an r-value. However, the rvalue reference is said to be directly related to the temporary. Thus, for the purpose of resolving function overload

 void movetest(AA) void movetest(AA&&) 

are equal, since the implicit conversion sequences used to convert AA () to AA and AA & < , respectively, are equal. The first is not better, because direct link binding is also considered an identity conversion.

+6
source

Consistent with decltype. This is no different from this C ++ 03/98 uncertainty:

 struct AA {}; void movetest(AA s) {} void movetest(AA& s) {} int main() { AA a; movetest(a); } test.cpp:9:5: error: call to 'movetest' is ambiguous movetest(a); ^~~~~~~~ test.cpp:3:6: note: candidate function void movetest(AA s) {} ^ test.cpp:4:6: note: candidate function void movetest(AA& s) {} ^ 1 error generated. 
+1
source

Source: https://habr.com/ru/post/885470/


All Articles