Perfect forwarding and ref-qualifiers for member functions

138 Views Asked by At

C++11 introduced the ability to ref-qualify member functions, as well as perfect forwarding. But can we mix them together?

Consider this (working) example:

struct bar{
    std::string str;
    void do_stuff() & {
        /* version 1 */
    }
    void do_stuff() && {
        /* version 2 */
    }
};

struct foo{
    bar data;
    void do_stuff() & {
        data.do_stuff();
    }
    void do_stuff() && {
        std::move(data).do_stuff();
    }
};

int main(){
    foo f;
    f.do_stuff() // calls version 1 of bar::do_stuff()
    std::move(f).do_stuff() // calls version 2 of bar::do_stuff()
}

Inside main(), the first call calls version 1 or bar::do_stuff() and the second call calls version 2 or bar::do_stuff(). There is some duplication of code in foo::do_stuff(). If the ref-qualifiers were for an argument other than the implied *this, we could easily do perfect forwarding:

template <typename T>
void do_stuff (T&& t) {
    std::forward<T>(t).do_stuff();
}

Is there an equivalent way to perfectly forward the *this object?

Note: If the proper solution only exists in C++14 or C++17, I'd be happy to know too.

0

There are 0 best solutions below