static compile time table with floating point values

前端 未结 2 345
你的背包
你的背包 2021-01-14 21:38

Is it possible to generate an array at compile time, like in this nice answer of G. Fritzsche: Georg Fritzsche

but with floating point values?

2条回答
  •  日久生厌
    2021-01-14 22:18

    Here is a solution creating an array of doubles which takes an initialization class to map an int index to a suitable value. The example create an array with 20 value approximating sin(x) for 20 values in the range [0, 2π]. Most of the code is devoted to producing a sequence of integers [0...N): if that operation is readily available, the code becomes fairly trivial (it is being added to C++14; see n3493).

    #include 
    #include 
    
    template  struct indices {};
    template  struct make_list;
    template 
    struct make_list<0, indices > {
        typedef indices<0, Indices...> type;
    };
    
    template 
    struct make_list > {
        typedef typename make_list >::type type;
    };
    
    template  struct array_aux;
    template 
    struct array_aux >
    {
        static double const values[N];
    };
    
    template 
    double const array_aux >::values[N] = {
        Init::value(Indices)...
    };
    
    template 
    struct array
        : array_aux >::type>
    {
    };
    
    
    
    struct init_sin
    {
        static constexpr double value(int index) {
            return std::sin(index * 2.0 * 3.1415 / 20.0);
        }
    };
    
    int main()
    {
        for (int i = 0; i != 20; ++i) {
            std::cout << array::values[i] << "\n";
        }
    }
    

    If the generator function, i.e., Init::value() is a constexpr function actually return constant values (probably not quite the case for std::sin()) the values can be computed at compile time. Otherwise they will be computed during static initialization.

提交回复
热议问题