STD::ARRAY ALGORITHM

Asked By 0 points N/A Posted on -
qa-featured

consider: static constexpr unsigned num_points {7810};

std :: array <double, num_points> axis;

for (int i = 0; i <num_points; ++ i)

{Axis [i] = 180 + 0.1 * i;}

The axis is a constant at the class level. I want to avoid initializing it like any other global variable. Can it be done at compile time?

SHARE
Answered By 30 points N/A #318496

STD::ARRAY ALGORITHM

qa-featured

For the sake of completeness, here is a version that does not require the definition of a function, but instead uses a lambda. C ++ 17 introduced the possibility of using lambdas in constant expressions. You can therefore declare your table constexpr and initialize it with a lambda:

static auto constexpr static = [] {

std :: array <double, num_points> a {};

for (int i = 0; i <num_points; ++ i) {

a [i] = 180 + 0.1 * i;

}return one;} ();

(Note the () in the last line, which immediately calls the lambda.)

If you do not like the car in the axis declaration because the reading of the real type is difficult, but you do not want to repeat the type in lambda, you can do the following:

static constexpr std :: array <double, num_points> axis = [] {

auto a = decltype (axis) {};

for (int i = 0; i <num_points; ++ i) {

a [i] = 180 + 0.1 * i;}

return one;} ();

Related Questions