我有一个这样的函数模板:
template <class ...A>
do_something()
{
// i'd like to do something to each A::var, where var has static storage
}
我不能使用 Boost.MPL
。你能告诉我如何在没有递归的情况下做到这一点吗?
编辑:这些天 (c++17),我会这样做:
template <class ...A>
do_something()
{
((std::cout << A::var << std::endl), ...);
};
最佳答案
什么Xeo said .为了创建包扩展的上下文,我使用了一个什么都不做的函数的参数列表(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
。
关于c++ - 迭代可变参数模板的类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15501322/