iterating over variadic template's type parameters

前端 未结 2 1250
忘掉有多难
忘掉有多难 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:47

    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 
    #include 
    
    template 
    struct Int {
        static const int var = i;
    };
    
    template 
    void do_something(std::initializer_list list) {
        for (auto i : list)
            std::cout << i << std::endl;
    }
    
    template 
    void expand(A&&...) {
    }
    
    template 
    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<2>, Int<3>>();
    }
    

提交回复
热议问题