将移动语义隐藏在单个函数后面
Hiding move semantics behind single function
例如,我有一个可以处理const T &
和T &&
值的函数:
template <typename T>
/* ... */ foo(const T &) {
std::cout << "const T & as arg" << std::endl;
}
template <typename T>
/* ... */ foo(T &&) {
std::cout << "T && as arg" << std::endl;
}
有没有一种方法可以让我编写一个单独的函数,自动处理这两种类型?如:
template <typename T>
/* ... */ bar(T t) {
foo(t);
}
因此:
T a;
bar(a); // Handles as const T &
T b;
bar(std::move(b)); // Handles as T &&
谢谢!
您可以使用引用折叠和std::forward
将参数转发到foo
函数:
template <typename T>
/* ... */ bar(T&& t) {
foo(std::forward<T>(t));
}
请注意,您的foo
函数将接受右值、常值和非常值。举个例子,给定:
const int x = 456;
int y = 123;
然后:
foo(123); // foo(T&&)
foo(x); // foo(const T&)
foo(y); // foo(T&&)
现场演示
相关文章:
- C++调用具有 *this 属性的单个帮助程序函数
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- 如何在 c++ 中将整个数组初始化为类构造函数中的单个元素
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 多个可变参数函数的单个模板参数包?
- 将指向多维数组向量中的单个项的指针传递给函数 c++
- 如何将多个函数重载作为单个参数传递?
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 如何使用 TBB 在单个线程中运行函数
- 模板化虚拟函数,管理单个类的不同类属性
- 如何对具有相同类型的成员使用单个函数 C++.
- 如何使用每个对象的单个构造函数参数动态分配C++对象数组?
- 外部 C 和 C++ 对于单个函数(bsearch / qsort)的目的是什么?
- 如何使用 std::cout 或 std::ofstream 作为单个函数的输入?
- C 使用单个函数对具有多种值类型的数组排序
- 如何使用单个对象调用具有相同名称的两个类函数
- 如何在C 中的单个构造函数中调用多个构造函数
- C++ 中深度嵌套函数的单个捕获全部语句?
- C :类 - 超载构造函数 - 单个变量