In C++, a function with signature void f(A& a) (non-template) only binds to a lvalue.
Is it possible for an rvalue to automatically cast itself to an lvalue?
This is what I tried:
#include <cassert>
#include <utility>
struct A {
operator A&() && {
return *this;
}
void mutate() {...}
};
This produces a compiler warning, "converting 'A' to a reference to the same type will never use a type conversion". But at least the operator is compiled and works, except that it needs to be explicitly called with the full .operator A&() syntax.
void f(A& a) { a.mutate(); }
A make_A() { return A{}; }
int main() {
A a;
f(a); // ok
f(make_A().operator A&()); // ok
f(make_A()); // does not compile, implicit conversion to A& doesn't work
f(std::move(a)); // does not compile
}
https://godbolt.org/z/oKM8n5z1E
A similar question was asked before Rvalue to lvalue conversion? that shows how to do this. In my case, I want to enable this, but only for a specific class.
Is there a trick or workaround to achieve this?
auto as_lvalue(std::string&& s) -> std::string& { return s; }would spoof the rvalue as being an lvalue. Kind of the opposite ofstd::move.