Search code examples
c++rvalue-referencelvalue

Choose function declaration with lvalue or rvalue parameter


Is there a way to remove the 'plumb' version of all of my functions, without the need to change the 'hit' line to the 'fixed'?

Yes my program works fine, but I think if is there a way to get ride from this version of all of my functions.

Keep in mind that int is not really int in my programs, but a type alias which can be object ( e.g. container_reference<std::array<double,4>> ) or reference ( e.g. std::array<double,4> & )

void func(int &&m) { cout << "rvalue: " << m << endl; }
void func(int  &m) { cout << "lvalue: "; func(std::move(m)); } // PLUMB!

int main() 
{
    int a = 5;
    func(a);    // HIT!
    func(std::move(a)); // FIXED!
    func(6);
    func(a + 5);
}

Solution

  • I'm having a bit of trouble understand exactly what you want, but this might be an option:

    template<typename T>
    void func(T &&m) {
      // ...
    }
    

    T&& has been dubbed "universal reference" as it will bind to both lvalues and rvalues due to reference collapsing rules.