【发布时间】:2017-08-16 19:00:16
【问题描述】:
我想用实现相同功能的可变参数模板替换这些宏。
#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)
因为你不能引用右值。
我怎样才能在这两种情况下都做到这一点?
【问题讨论】:
-
你提到的宏呢?我想它会产生同样的错误。无论如何,将某些东西分配给像 5 这样的文字是没有意义的。或者,您是否打算仅在最后一个位置放置右值?
-
@JunekeyJeon 正确。在最后一个位置只会有一个右值。
标签: c++ c++11 templates variadic-templates variadic-functions