我想用预定的序列初始化一个静态(并且可能是常量)数组。
在这种特殊情况下,它将是一个正弦表,其中包含数字化的正弦波。

现在,我知道您可以使用以下方法初始化数组:

#define TABLE_SIZE 2000
static float table[TABLE_SIZE] = { 0 , 0.124 , 0.245 , ...  }

我需要做的就是生成所有正弦值并将其粘贴到内部,但是我认为这非常丑陋。

是否有一个预处理器 指令 lambda 函数或用于此的东西?

失败了,这仅仅是在程序开始时计算所有值并将它们分配给静态数组的一种解决方案?

编辑:

感谢Templatetx的c++11: Create 0 to N constexpr array in c++答复
,我有一个可行的解决方案:
#define TABLE_SIZE 2000
template<class Function, std::size_t... Indices>
    constexpr auto make_array_helper(Function f, std::index_sequence<Indices...>)
-> std::array<typename std::result_of<Function(std::size_t)>::type, sizeof...(Indices)>
{
    return {{ f(Indices)... }};
}

template<int N, class Function>
constexpr auto make_array(Function f)
-> std::array<typename std::result_of<Function(std::size_t)>::type, N>
{
    return make_array_helper(f, std::make_index_sequence<N>{});
}

constexpr float fun(double x) { return (float)sin(((double)x / (double)TABLE_SIZE) * M_PI * 2.0); }

static constexpr auto sinetable = make_array<TABLE_SIZE>(fun);

不幸的是,我很难将其整合到类里面。
出现错误:sinetable::make_array is used before its definition,我猜是因为静态成员是在静态方法之前定义的。或者也许与constexpr内联有关。

最佳答案

您正在寻找的是C++ 11的constexpr,但是您需要递归模板。

c++11: Create 0 to N constexpr array in c++

http://fendrich.se/blog/2012/11/22/compile-time-loops-in-c-plus-plus-11-with-trampolines-and-exponential-recursion/

但是,C++的标准数学函数不是constexpr,因此您无论如何都无法使用它们,因此最好以常规方式在某个地方对其进行初始化。

07-24 09:52
查看更多