Template-ing a 'for' loop in C++?

后端 未结 10 639
没有蜡笔的小新
没有蜡笔的小新 2020-12-25 12:58

I have a C++ snippet below with a run-time for loop,

for(int i = 0; i < I; i++)
  for (int j = 0; j < J; j++)
    A( row(i,j), column(i,j)         


        
10条回答
  •  無奈伤痛
    2020-12-25 13:35

    This is the way to do it directly:

    template 
    struct inner
    {
      static void value()
      {
        A(row::value, column::value) = f::value;
        inner::value();
      }
    };
    
    template  struct inner { static void value() {} };
    
    template 
    struct outer
    {
      static void value()
      {
        inner::value();
        outer::value();
      }
    };
    
    template <> struct outer { static void value() {} };
    
    void test()
    {
      outer<0>::value();
    }
    

    You can pass A through as a parameter to each of the values if necessary.

    Here's a way with variadic templates that doesn't require hard coded I and J:

    #include 
    
    template 
    struct Inner;
    
    template 
    struct Outer;
    
    template 
    struct Inner>
    {
      static void value() { (A(column::value, row::value), ...); }
    };
    
    
    template 
    struct Outer, Columns>
    {
      static void value() { (Inner::value(), ...); }
    };
    
    template 
    void expand()
    {
      Outer, std::make_index_sequence>::value();
    }
    
    void test()
    {
      expand<3, 5>();
    }
    

    (snippet with generated assembly: https://godbolt.org/g/DlgmEl)

提交回复
热议问题