I have the following code, in which I overload the member function test::f
for both lvalue
and rvalue
to *this
#include <iostream>
struct test{
void f() &{ std::cout << "lvalue"; }
void f() &&{ std::cout << "rvalue"; }
};
int main(){
test tst;
tst.f(); // lvalue, outputs "lvalue"
// make it a rvalue reference
std::move(tst).f(); // rvalue, outputs "rvalue"
}
Everything works as expected. However, if I add const
-ness to BOTH test::f()
, such as
void f() const &{ std::cout << "lvalue"; }
void f() const &&{ std::cout << "rvalue"; }
the code doesn't compile anymore, spitting the error
error: call of overloaded 'f()' is ambiguous
What exactly is happening here? Why f
suddenly becomes ambiguous? Is it because a rvalue
can bind to a const
reference also, and the reference collapsing comes into play, i.e. the type becomes && & -> &, i.e. lvalue
? I don't really understand if this is the reason.
PS: just found out from @T.C. that the code compiles on clang no matter the const
-ness of f
. It seems to fail for const
member functions only on g++ (4.8 / 4.9) (BUT compiles on g++4.10)
PPS: Case closed, question is indeed a dupe, it is indeed a g++ bug, see the link Overload resolution with ref-qualifiers