In C++ I have this struct from C. This code is very old and cannot be modified:
struct Point {
double coord[3];
};
On the other hand, I have this modern function which returns modern std::array instead of raw arrays:
std::array<double, 3> ComputePoint();
Currently, to initialize a Point from the returned value, I manually extract each element from the std::array:
std::array<double, 3> ansArray{ComputePoint()};
Point ans{ansArray[0], ansArray[1], ansArray[2]};
This solution is feasible because there are only three coordinates.
Could I templatize it for a general length?
I would like something similar to the opposite conversion: std::to_array.
You can use
std::applyto do it for any length:If you run into this pattern a lot, it could be worth making a convenience function template:
See live example at Compiler Explorer
All the
std::forwarding isn't strictly necessary ifArgsis only going to be fundamental types likeintanddouble. In that case, you can omit it.