Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...