c++ - 迭代可变参数模板的类型参数

标签 c++ templates variadic-templates

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

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/

相关文章:

c++ - 从0到7生成8个唯一的随机数

c++ - 从类型名称列表中提取 C++ 变体类型

c++ - 比较两个类型的多重集是否相等

c++ - 检查是否有效的模板特化

c++ - 从模板化父类中的派生内部类访问 protected 成员变量

c++ - 当构造函数具有相同的参数类型(文件路径)时,如何从数组创建(初始化)std::tuple

c++ - 如何使用转换构造函数来初始化 vector

c++ - 使用私有(private)参数调用公共(public)函数

c++ - 我怎么知道我的 `std::chrono::high_resolution_clock`对应于 `steady_clock`或 `system_clock`或其他别名?

c++ - 从函数体中推导模板参数