解开variadic参数并相应地传递元素
假设我得到了一个结构IE coord
包含两个静态成员变量,然后将其作为variadic Template函数的参数传递给它variadic_print_coord()
,我如何解开variadic表达式,调用print_pair()
函数,如下所示。
template<class T1, class T2>
void print_pair(T1 t1, T2 t2)
{
std::cout << t1 << " and " << t2 << '\n';
}
template<class T1, class T2, class ...Ts>
void print_pair(T1 t1, T2 t2, Ts... ts)
{
print_pair(t1, t2);
print_pair(ts... );
}
template<int X, int Y>
struct Coord
{
static const int valueX = X;
static const int valueY = Y;
}
template<class... COORDs>
void variadic_print_coord()
{
print_pair(COORD1::valueX, COORD1::valueY, COORD2::valueX, COORD2::valueY, ...,
COORDs::valueX, COORDs::valueY);
//how could I manipulating the pack expressions to get something like this
}
int main()
{
print_pair<Coord<0,1>, Coord<2,3>, Coord<4,5>>();
//result:
//0 and 1
//2 and 3
//4 and 5
}
非常感谢!
suppose I got a struct i.e. Coord
that contains two static member variables, then pass it as an argument of variadic template function variadic_print_coord()
, how do I unpack the variadic expressions, to call the print_pair()
function that shown below.
template<class T1, class T2>
void print_pair(T1 t1, T2 t2)
{
std::cout << t1 << " and " << t2 << '\n';
}
template<class T1, class T2, class ...Ts>
void print_pair(T1 t1, T2 t2, Ts... ts)
{
print_pair(t1, t2);
print_pair(ts... );
}
template<int X, int Y>
struct Coord
{
static const int valueX = X;
static const int valueY = Y;
}
template<class... COORDs>
void variadic_print_coord()
{
print_pair(COORD1::valueX, COORD1::valueY, COORD2::valueX, COORD2::valueY, ...,
COORDs::valueX, COORDs::valueY);
//how could I manipulating the pack expressions to get something like this
}
int main()
{
print_pair<Coord<0,1>, Coord<2,3>, Coord<4,5>>();
//result:
//0 and 1
//2 and 3
//4 and 5
}
many thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,您可以使用涉及折叠表达式的以下构造
,您不需要
print_pair
的variadic版本,因为调用基本上是截断。You can use the following construct involving a fold expression
In this case you won't need the variadic version of
print_pair
, as the calls basically decouple.