简单移动参数时使用函数模板参数的优点

Advantages of using a function template argument when simply moving the parameter

考虑以下存储函数的结构:

struct yyy {
    std::function<int()> myFunc;

    void set_func_1(std::function<int()>&& f) {
        myFunc = std::move(f);
    }

    template<typename funcT>
    void set_func_2(funcT&& f) {
        myFunc = std::move(f);
    }
};

根据 this answer,我知道使用模板参数允许编译器优化内容。

但是对于上面的结构,我直接移动函数来存储它,使用模板参数有什么好处吗?

&& 参考资料,尽管拼写相同,但作用不同。

void set_func_1(std::function<int()>&& f) {
    myFunc = std::move(f);
}

是正确的,但只采用 r 值引用。在 template<typename funcT> void set_func_2(funcT&& f) 中,&& 是一个 转发引用 ,因此在正文中使用 std::move(f) 是错误的 - 它可能会从非临时对象窃取状态.相反,您需要使用 std::forward<funcT>(f).

与第一个功能相比,第二个功能的优势不是优化。第一个只接受 r 值,例如function<int> f = []{return 1;}; struct yyy; yyy.set_func_2(f); 不会编译。

编写 set() 方法的一种好的、简单的、近乎最佳的方法是按值传递和移动:

    void set_func_3(std::function<int()> f) {
    myFunc = std::move(f);
}

"Modern effective C++" Scott Meyers 的书对其适用性有更多详细信息。