我想用实现相同功能的可变参数模板替换这些宏。
#define SHFT2( a, b, c ) do { (a) = (b); (b) = (c); } while(0)
#define SHFT3( a, b, c, d ) do { (a) = (b); (b) = (c); (c) = (d); } while(0)
#define SHFT4( a, b, c, d, e ) do { (a) = (b); (b) = (c); (c) = (d); (d) = (e); } while(0)
我有一个适用于左值的解决方案
template<typename T, typename... Ts>
T first(T t, Ts... ts)
{
return t;
}
template<typename T>
void shift(T t)
{
// do nothing
}
template<typename T, typename... Ts>
void shift(T& t, Ts&... ts)
{
t = first(ts...);
shift(ts...);
}
例如,这行得通
int w = 1;
int x = 2;
int y = 3;
int z = 4;
shift(w, x, y, z);
printf("%d %d %d %d\n", w, x, y, z); // 2 3 4 4
但我希望能够在最后移入一个右值
shift(w, x, y, z, 5);
printf("%d %d %d %d\n", w, x, y, z); // expect 2 3 4 5
我收到这个错误
test.cpp:31:2: error: no matching function for call to 'shift'
shift(w, x, y, z, 5);
^~~~~
test.cpp:16:6: note: candidate function [with T = int, Ts = <int, int, int, int>] not viable: expects an l-value for 5th
argument
void shift(T& t, Ts&... ts)
^
test.cpp:10:6: note: candidate function template not viable: requires single argument 't', but 5 arguments were provided
void shift(T t)
因为您不能引用右值。
我怎样才能使这两种情况都有效?
最佳答案
您可以使用转发引用参数来接受左值和右值,以及std::forward
“转发”原始参数的值类别,即将参数转换为匹配的值类别。
template <typename T>
void shift(T&& t) {
// do nothing
}
template<typename T1, typename T2, typename... Ts>
void shift(T1&& t1, T2&& t2, Ts&&... ts) {
std::forward<T1>(t1) = std::forward<T2>(t2);
shift(std::forward<T2>(t2), std::forward<Ts>(ts)...);
}
在这里,std::forward<T1>(t1)
确保 t1
如果参数是左值,将被分配为左值,如果参数是右值,则将被分配为右值。例如,shift(42, x)
不会编译,因为类型为 int
的右值无法分配给。
std::forward<T2>(t2)
确保如果 t2
的参数是一个左值,它将被复制,而如果它是一个右值,它将尽可能被移动。
std::forward<T2>(t2)
和 std::forward<Ts>(ts)...
将值类别信息传递给递归调用。
关于c++ - 如何创建可变参数模板函数来移动参数值并处理左值和右值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42989335/