I have a struct
that holds an array, and I'd like to pass an initializer list to the struct's constructor to be forwarded on to the array. To illustrate, I tried:
#include <initializer_list>
struct Vector
{
float v[3];
Vector(std::initializer_list<float> values) : v{values} {}
};
int main()
{
Vector v = {1, 2, 3};
}
error: cannot convert ‘std::initializer_list<float>’ to ‘float’ in initialization
I tried using parentheses instead of braces for v
but that gave the error:
error: incompatible types in assignment of ‘std::initializer_list<float>’ to ‘float [3]’
My main motivation for trying to do this is to avoid the following warning that clang generates:
template <int N>
struct Vector
{
float v[N];
};
template <>
struct Vector<2>
{
float x, y;
};
int main()
{
Vector<2> v2 = {1.0f, 2.0f}; // Yay, works
Vector<3> v3 = {1.0f, 2.0f, 3.0f}; // Results in warning in clang++
Vector<3> u3 = {{1.0f, 2.0f, 3.0f}}; // Must use two braces to avoid warning
// If I could make Vector<N> take an initializer list in its constructor, I
// could forward that on to the member array and avoid using the double braces
}
warning: suggest braces around initialization of subobject
So my question is: How can I initialize a member array with an initializer list? (i.e. How can I make the first code work? Or is it not possible?