iterating over variadic template's type parameters

前端 未结 2 1252
忘掉有多难
忘掉有多难 2020-12-14 18:19

I have a function template like this:

template 
do_something()
{
  // i\'d like to do something to each A::var, where var has static storag         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 18:37

    What Xeo said. To create a context for pack expansion I used the argument list of a function that does nothing (dummy):

    #include 
    #include 
    
    template
    void dummy(A&&...)
    {
    }
    
    template 
    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();
        std::cout << S1::var << S2::var << S3::var;
    }
    

    This program prints 111.

提交回复
热议问题