Is there an elegant way to create and initialize a const std::vector
like const T a[] = { ... }
to a fixed (and small) number of val
Based on Shadow2531's response, I'm using this class to initialise vectors, without actually inheriting from std::vector like Shadow's solution did
template
class vector_init
{
public:
vector_init(const T& val)
{
vec.push_back(val);
}
inline vector_init& operator()(T val)
{
vec.push_back(val);
return *this;
}
inline std::vector end()
{
return vec;
}
private:
std::vector vec;
};
Usage:
std::vector testVec = vector_init(1)(2)(3)(4)(5).end();
Compared to Steve Jessop's solution it creates a lot more code, but if the array creation isn't performance critical I find it a nice way to initialise an array in a single line