迭代可变参数模板的类型参数 [英] iterating over variadic template's type parameters
本文介绍了迭代可变参数模板的类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的功能模板:
I have a function template like this:
template <class ...A>
do_something()
{
// i'd like to do something to each A::var, where var has static storage
}
我不能使用 Boost.MPL
。
推荐答案
什么 Xeo说。为了创建包扩展的上下文,我使用了一个不做任何事情的函数的参数列表( dummy
):
What Xeo said. To create a context for pack expansion I used the argument list of a function that does nothing (dummy
):
#include <iostream>
#include <initializer_list>
template<class...A>
void dummy(A&&...)
{
}
template <class ...A>
void do_something()
{
dummy( (A::var = 1)... ); // set each var to 1
// alternatively, we can use a lambda:
[](...){ }((A::var = 1)...);
// or std::initializer list, with guaranteed left-to-right
// order of evaluation and associated side effects
auto list = {(A::var = 1)...};
}
struct S1 { static int var; }; int S1::var = 0;
struct S2 { static int var; }; int S2::var = 0;
struct S3 { static int var; }; int S3::var = 0;
int main()
{
do_something<S1,S2,S3>();
std::cout << S1::var << S2::var << S3::var;
}
此程式列印 111
。
这篇关于迭代可变参数模板的类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文