I have a legacy function that takes an argument by T&
, in modern C++ this should have been a T&&
from the start.
e.g.
namespace old_space {
template<class T>
void f(T& t) {...}
}
Currently I have to do this for it to work,
MyType v = g(1);
old_space::f(v);
The function refuses to take, even in principle, a temporary rvalue.
old_space::f(g(1));
I know that there can be no leaks or dangling references and it would be actually ok to accept an rvalue.
(This is because the very nature of MyType
, which a simulated reference.)
I can't overload f
, in the original or any namespace.
Also, I want a solution that works for MyType
only and not for any random type.
It occurred to me that I could have conversion operator to an lvalue.
struct MyType {
...
operator MyType& operator()&& {return *this;}
};
I though it was an elegant idea, however it didn't work (f
can't still capture f(g(1))
.
Also the compiler complained that error: converting ‘MyType’ to a reference to the same type will never use a type conversion operator [-Werror=class-conversion]
if I activate warnings, which is probably true but I don't know why also.
The question is, can I adapt struct MyType
in any way so that f(g(1))
is valid syntax, where g(1)
generates a new value of MyType
and f
's signature is template<class T> void f(T&)
.
I also tried this, but still didn't work:
template<class T, std::enable_if_t<std::is_same<T, MyType>::value, int> =0>
operator T&() && {return *this;}