带有浮点值的静态编译时间表 [英] static compile time table with floating point values

查看:74
本文介绍了带有浮点值的静态编译时间表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在编译时生成数组,例如G. Fritzsche的好结果:
Georg Fritzsche

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

但具有浮点值?

不可能以这种方式,因为,递归发生的可变扩展需要编译时const值?

I think its not possible in this manner because, the variadic expansion which happens by the recursion needs compile time const values?

是否有另一种方法来生成编译时浮点数组,在编译时计算复杂的函数,或者这只限于整数类型的算术?

Is there another way to generate compile time floating point arrays, with meta functions which calculate something complex at compile time or is this restricted only to arithmetic of integral types?

感谢您的输入! : - )

Thanks for the input! :-)

推荐答案

下面是一个创建 double s,它接受一个初始化类来将 int 索引映射到合适的值。该示例为范围 [0,2π]中的20个值创建具有近似于 sin(x)的20值的数组。大多数代码专用于产生整数序列 [0 ... N] :如果该操作可用,代码变得相当微不足道(它被添加到C ++ 14;请参阅 n3493 )。

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 <iostream>
#include <cmath>

template <int...> struct indices {};
template <int N, typename> struct make_list;
template <int... Indices>
struct make_list<0, indices<Indices...> > {
    typedef indices<0, Indices...> type;
};

template <int N, int... Indices>
struct make_list<N, indices<Indices...> > {
    typedef typename make_list<N-1, indices<N, Indices...> >::type type;
};

template <typename Init, int N, typename> struct array_aux;
template <typename Init, int N, int... Indices>
struct array_aux<Init, N, indices<Indices...> >
{
    static double const values[N];
};

template <typename Init, int N, int... Indices>
double const array_aux<Init, N, indices<Indices...> >::values[N] = {
    Init::value(Indices)...
};

template <typename Init, int N>
struct array
    : array_aux<Init, N, typename make_list<N-1, indices<> >::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<init_sin, 20>::values[i] << "\n";
    }
}

如果生成函数,即 Init :: value()是一个 constexpr 函数实际上返回常量值(可能不是这样的 std :: sin()),可以在编译时计算这些值。否则,它们将在静态初始化期间计算。

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.

这篇关于带有浮点值的静态编译时间表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆