【发布时间】:2017-02-17 13:34:01
【问题描述】:
我想用预定的顺序初始化一个 big 静态(可能是常量)数组。 在这种特殊情况下,它将是一个正弦表,包含一个数字化的正弦波。
现在,我知道您可以使用以下方法初始化数组:
#define TABLE_SIZE 2000
static float table[TABLE_SIZE] = { 0 , 0.124 , 0.245 , ... }
我需要做的就是生成所有正弦值并将它们粘贴到里面,但在我看来这非常丑陋。
是否有 预处理器 指令或 lambda 函数或用于此目的的东西?
如果做不到这一点,只是在程序开始时计算所有值并将它们分配给静态数组的解决方案?
编辑:
感谢 TemplateRex 来自 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吗? -
看看我的老答案 :) stackoverflow.com/questions/35389493/…。纯粹的丑陋!只需定义 2000 个宏就可以了。
-
You have 2x
returninfunbody :) 我仍然认为这是一个 hack,float[N]与std::array<float, N>不同 :(
标签: c++ arrays static initialization c-preprocessor