C++11: Compile Time Calculation of Array

前端 未结 7 2084
长发绾君心
长发绾君心 2020-11-28 05:25

Suppose I have some constexpr function f:

constexpr int f(int x) { ... }

And I have some const int N known at compile time:

Either<

相关标签:
7条回答
  • 2020-11-28 06:19

    If you want the array to live in static memory, you could try this:

    template<class T> struct id { typedef T type; };
    template<int...> struct int_pack {};
    template<int N, int...Tail> struct make_int_range
        : make_int_range<N-1,N-1,Tail...> {};
    template<int...Tail> struct make_int_range<0,Tail...>
        : id<int_pack<Tail...>> {};
    
    #include <array>
    
    constexpr int f(int n) { return n*(n+1)/2; }
    
    template<class Indices = typename make_int_range<10>::type>
    struct my_lookup_table;
    template<int...Indices>
    struct my_lookup_table<int_pack<Indices...>>
    {
        static const int size = sizeof...(Indices);
        typedef std::array<int,size> array_type;
        static const array_type& get()
        {
            static const array_type arr = {{f(Indices)...}};
            return arr;
        }
    };
    
    #include <iostream>
    
    int main()
    {
        auto& lut = my_lookup_table<>::get();
        for (int i : lut)
            std::cout << i << std::endl;
    }
    

    If you want a local copy of the array to work on, simply remove the ampersand.

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