简体   繁体   中英

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
}

I can't use Boost.MPL . Can you please show how to do this without recursion?

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;
}

This program prints 111 .

As an example, suppose you want to display each A::var. I see three ways to acomplish this as the code below illustrates.

Regarding option 2, notice that the order in which the elements are processed is not specified by the standard.

#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>>();
}

The answers above work -- here I explore a bit more on using a lambda for complex use cases.

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

If you want to expand a lambda with a variadic template, it won't work as mentioned above when the parameters is of a non-trivial type:
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 .

The way to go is to move the code from the lambda's args to code :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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