繁体   English   中英

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

[英]iterating over variadic template's type parameters

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

template <class ...A>
do_something()
{
  // i'd like to do something to each A::var, where var has static storage
}

我不能使用Boost.MPL 你能展示如何在没有递归的情况下做到这一点吗?

Xeo说的是什么。 要为包扩展创建上下文,我使用了不执行任何操作的函数的参数列表( 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

例如,假设您要显示每个A :: var。 我看到了三种方法来实现这一点,如下面的代码所示。

关于选项2,请注意标准未指定处理元素的顺序。

#include <iostream>
#include <initializer_list>

template <int i>
struct Int {
    static const int var = i;
};

template <typename T>
void do_something(std::initializer_list<T> list) {
    for (auto i : list)
        std::cout << i << std::endl;
}

template <class... A>
void expand(A&&...) {
}

template <class... A>
void do_something() {

    // 1st option:
    do_something({ A::var... });

    // 2nd option:
    expand((std::cout << A::var << std::endl)...);

    // 3rd option:
    {
        int x[] = { (std::cout << A::var << std::endl, 0)... };
        (void) x;
    }
}

int main() {
    do_something<Int<1>, Int<2>, Int<3>>();
}

上面的答案有效——在这里,我将更多地探讨如何将 lambda 用于复杂的用例。

Lambda 101: [ capture ]( params ){ code }( args to call "in-place" );

如果你想用可变参数模板扩展 lambda,当参数是非平凡类型时,它不会像上面提到的那样工作:
error: cannot pass object of non-trivial type 'Foo' through variadic method; call will abort at runtime error: cannot pass object of non-trivial type 'Foo' through variadic method; call will abort at runtime

要走的路是将代码从 lambda 的argscode

template <class ...A>
do_something() {
  Foo foo;
  [&foo](var...){
    foo.DoSomething(var);
  }(A::var...);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM