5

C++11 引入了 ref-qualify 成员函数以及完美转发的能力。但是我们可以将它们混合在一起吗?

考虑这个(工作)示例:

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()
}

在内部main(),第一个调用调用版本 1 or bar::do_stuff(),第二个调用调用版本 2 or bar::do_stuff()。中存在一些重复的代码foo::do_stuff()。如果 ref-qualifiers 用于除了隐含之外的参数*this,我们可以轻松地进行完美转发:

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

有没有一种等效的方法可以完美地转发*this对象?

注意:如果正确的解决方案只存在于 C++14 或 C++17 中,我也很乐意知道。

4

0 回答 0