Search code examples
c++rvalue-reference

How copy existing object and cast the copy into r-value reference in a single expression


Is there a quick and expressive way to make a copy of an existing object and pass it into r-value reference? I've an existing API that takes r-value references as parameter. But I can't change it due to backwards compatibility nor I can overload it because of the shear amount of overloads it have already. For example, foo is my existing API.:

void foo(int&& n)
{
    do_something(std::forward<int>(n));
}


int main()
{
    int n = get_value();

    // foo(n); // Doesn't work. Passing value into rvalue reference
    int n_ = n;
    foo(std::move(n)) // Works but ugly.

    foo(std::make_copy_and_move_said_copy(n));
    
    other_function(n);
}

Is there a way to implement make_copy_and_move_said_copy? Or is it impossible in the language.


Solution

  • You can make a copy like this:

    foo(+n);
    

    or this:

    foo(int(n));
    

    or in a more generic way like this:

    foo(decltype(n)(n));