Excellent forwarding and ref qualifiers for member functions

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, the main()first call calls version 1 or bar::do_stuff(), and the second call calls version 2 or bar::do_stuff(). There foo::do_stuff()is some duplication of code. If ref-qualifiers were for an argument other than the implied *this, we could easily make a great forward:

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

Is there an equivalent way to perfectly redirect an object *this?

Note. If the right solution exists only in C ++ 14 or C ++ 17, I would also be happy to know.

+4

Source: https://habr.com/ru/post/1677824/


All Articles