I'm trying to get extended variant of std::array
for math vectors (and expose same interface as array
does without boilerplate code). I know about std::valarray
but I want fixed size for proper typing in matrix multiplications. Thus I array
fits perfectly. But when I try to inherit constructor it fails.
struct vec2d : std::array<float, 2>
{ using array::array; }; // simplified
struct vec : std::vector<float>
{ using vector::vector; };
std::array<float, 2> x = {1, 2};
vec y = {1, 2};
vec2d z = {1, 2}; // error: could not convert ‘{1, 2}’
// from ‘<brace-enclosed initializer list>’ to ‘vec2d’
This error reported for GCC 4.8.2 and for clang 3.4. Last says that vec2d
have only implicit default/copy/move constructors. Yes, array
have only implicit ctor in contrary to vector
which have ctor from initializer_list
. But since ctors are inherited it is natural to inherit possibility to initialize it in a same way as array
initialized.
Question: Why we have that error instead of expected behavior (similar to array
initialization)?
Note: I that I can write forwarding manually to make it work, but this doesn't look as elegant as ctor inheritance.
struct vec2d : std::array<float, 2>
{
using array::array;
// nasty boilerplate code I don't want to have in C++11
template <typename... Args>
vec2d(Args &&... args) : array({float(std::forward<Args>(args))...}) {}
};
See Question&Answers more detail:os