我想用一個預先確定的序列初始化一個大的靜態(可能是常量)數組。 在這種特殊情況下,它將成爲一個可調節的,包含數字化的正弦波。帶序列的靜態(成員)數組的優雅初始化
現在,我知道你可以初始化數組:
#define TABLE_SIZE 2000
static float table[TABLE_SIZE] = { 0 , 0.124 , 0.245 , ... }
和所有我需要做的是生成所有的正弦值,並將其粘貼裏面,但在我看來這是非常醜陋。
是否有預處理指令或拉姆達功能或東西嗎?
失敗了,只是一個解決方案來計算程序開始時的所有值,並將它們分配給靜態數組?
編輯:
由於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'嗎? – Rakete1111
看看我很老的答案:) http://stackoverflow.com/questions/35389493/is-it-possible-to-evaluate-array-on-compilation-time/35390025#35390025。純粹的醜陋!只需定義2000個宏,你就很好。 – xinaiz
你在'fun'中有2個'return' :)我仍然認爲這是一個黑客,'float [N]'與'std :: array不一樣'':( –
xinaiz