Is it possible to create and initialize an array of values using template metaprogramming?

前端 未结 7 747
悲&欢浪女
悲&欢浪女 2020-12-04 22:20

I want to be able to create an array of calculated values (let\'s say for simplicity\'s sake that I want each value to be the square of it\'s index) at compile time using t

相关标签:
7条回答
  • 2020-12-04 23:15

    I really like j_random_hackers answer - its beautiful and short. With C++11, one can extend this to

    template <int I>
    struct squared {
      squared<I - 1> rest;
      static const int x = I * I ;
      constexpr int operator[](int const &i) const { return (i == I ?  x : rest[i]); }
      constexpr int size() const { return I; }
    };
    
    template <>
    struct squared<0> {
      static const int x = 0;
      constexpr int operator[](int const &i) const { return x; }
      constexpr int size() const { return 1; }
    };
    

    This code is usable both at run time

      squared<10> s;
    
      for(int i =0; i < s.size() ; ++i) {
        std::cout << "s[" << i << "]" << " = " << s[i] << std::endl;
      }
    

    as well as compile time

    struct Foo {
      static const squared<10> SquareIt;
      enum { 
        X = 3,
        Y = SquareIt[ X ]
      };
    };
    
    int main() {
      std::cout << "Foo::Y = " << Foo::Y << std::endl;
    }
    

    and provides a nice and readable syntax.

    0 讨论(0)
提交回复
热议问题