I would like to initialize a big static (and possibly constant) array with a predetermined sequence. In this particular case it would be a sinetable, containing a digitized sine-wave.
Now, I know you can initialize arrays with:
#define TABLE_SIZE 2000
static float table[TABLE_SIZE] = { 0 , 0.124 , 0.245 , ... }
and all I need to do is generate all the sine values and paste them inside, but in my opinion this is incredibly ugly.
Is there a preprocessor directive or a lambda function or something for this?
Failing that, just a solution to calculating all the values at the start of the program and assigning them to the static array?
EDIT:
Thanks to TemplateRex's answer from c++11: Create 0 to N constexpr array in c++ , I have a working solution:
#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);
Unfortunately I am having difficulties integrating this into a class.
Getting error : sinetable::make_array is used before its definition
, I'm guessing because static members are defined before static methods. Or maybe it has to do with constexpr
being inline.