Search code examples
c++c++11overloadingrvalue-referencestdmove

How to route to different implementations according to whether an object is a rvalue reference or not?


For example, I have a class called MyClass and create an instance from it:

auto obj = MyClass()

I have two ways to call its method.

Option 1: call the method directly

obj.method()

Option 2: cast obj to rvalue reference first, then call the method

std::move(obj).method()

I was wondering whether it is possible to create different implementation of method between Option 1 and Option 2. Is there a way to route/overload the method according to whether an object is a rvalue reference or not?


Solution

  • You can declare member functions with reference qualifiers. e.g.

    class MyClass {
    public:
        void method() & { std::cout << "on lvalue\n"; }
        void method() && { std::cout << "on rvalue\n"; }
    };
    

    then

    auto obj = MyClass();
    obj.method();            // invoke the lvalue version
    std::move(obj).method(); // invode the rvalue version
    

    Is there a way to route/overload the method according to whether an object is a rvalue reference or not?

    To be precise, which overloading is selected in overload resolution depends on whether the object to be called on is an lvalue or rvalue, not its type is rvalue reference or not. Types and value categories are two independent things.