samedi 21 juillet 2018

C++: initialize multidimensional array using lambdas

I want to initialize an array of doubles containing the first 4 powers of every one of three coefficients of two 3D vectors. I'm trying something like this now:

auto getPows = [](double x) { return {1.,x, x*x, x*x*x, x*x*x*x};};
const double allPows[2][3][5] = {
  {getPows(vec1.x()),getPows(vec1.y()),getPows(vec1.z())},
  {getPows(vec2.x()),getPows(vec2.y()),getPows(vec2.z())}
};

But it gives a compilation error:

error: returning initializer list

I've read that lambdas cannot return initializer list implicitly. Changing lambda definition to:

auto getPows = [](double x) -> std::initializer_list<double> { return {...};};

doesn't help:

error: cannot convert ‘std::initializer_list<double>’ to ‘const double’ in initialization

};

What's the right way to do it?

Aucun commentaire:

Enregistrer un commentaire