迭代可变参数模板的类型参数

新手上路,请多包涵

我有一个这样的函数模板:

 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), ...);
};

原文由 user1095108 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 499
1 个回答

谢欧说 的。为了创建包扩展的上下文,我使用了一个什么都不做的函数的参数列表( 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

原文由 jrok 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题