I have a template class that’s a simple vector, but this piece of code refuses to compile:
template<int t>
struct Vector {
int pos[t];
Vector(int other[t]) {
for (int i = 0;i < t;++i) {
pos[i] = other[i];
}
}
};
Vector<3> cake = {3,4,5};
This is the error:
Line 11: error: scalar object 'cake' requires one element in initializer
compilation terminated due to -Wfatal-errors.
Why doesn’t this work? What’s the simplest way to make it work similarly to this?
EDIT:
Neither does this work:
Vector<3> cake({3,4,5});
Isn’t that supposed to call a constructor with signature Vector<3>(int[3])?
In C++03, the initializer form of
{}is allowed for only aggregates (which includes POD also).The class template in code is not POD, neither is it aggregate. Read my answer here to know the definition of POD and Aggregate.
Once you know the definitions, you’ll know what you can do to make your class POD (if you want to).
However, in C++11, you can use
{}initializer, but you’ve usestd::initializer_list<T>as the parameter type of the constructor. Then you can use{}even for types which are not POD and Aggregate!