在简单地移动参数时使用函数模板参数的优点
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);
}
};
根据这个答案,我知道使用模板参数允许编译器优化内容。
但是对于上面的结构,我直接移动函数来存储它,使用模板参数有什么好处吗?
&&
引用,即使拼写方式相同,也起着不同的作用。
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);
}
斯科特·迈耶斯(Scott Meyers(的《现代有效C++》一书中详细介绍了其适用性。
相关文章:
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 具有常量引用参数的函数模板专用化
- 使用可变参数函数作为模板参数
- std::span<const T> 作为函数模板中的参数
- 如何在C++中伪造虚拟可变参数函数模板?
- C++ std::functional 中的可变参数函数模板
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 三个参数函数模板令人困惑的示例
- 父可变参数函数模板专门用于子级
- C++如何将可变参数函数模板的参数包 -> 包装到 lambda 中
- 将函数传递给可变参数函数模板
- 为什么可变参数函数模板中的这个 constexpr 不是常数?
- 将多个初始值设定项列表传递到可变参数函数模板时遇到问题
- 依赖类型不明确的 c++11 可变参数函数模板重载是否不明确
- 操作可变参数函数模板的函数参数
- C++11 中的非类型可变参数函数模板
- 将可变参数函数模板的每个参数传递给返回void的函数
- 包扩展不在最后一个参数中的可变参数函数模板
- 将可变参数函数模板参数存储到联合向量中的最有效方法
- Clang 和 GCC 在解决可变参数函数模板重载时的行为不同