I have a class that is templated with ints (i.e.:
template </*...*/, int a> /*...*/
). In my class, I would like a constructor that takes exactly “a” arguments. I can of course make it variadic, but I’d like compile-time checks on length if possible. I also think macro hacks could work, but I’m starting by looking for built-in C++ functionality.
Is this possible in C++, and how can it done if so?
Dealing with a sequence of values of the same type is what arrays are for.
You don’t even need to use raw arrays; with C++11 you can use
std::array.E.g. like so:
If your compiler doesn’t offer
std::arraythen you can very easily define a corresponding class, or you can just use a raw array:Hm, I hope I got the placement of
&correct there. For some reason that I can’t fathom, I always forget that syntax. No matter how many times I’ve used it.Given that the OP clarifies in a comment that (1) he doesn’t have C++11 and (2) he wants simple declaration syntax like
one possibility is to make
MyClassan aggregate that can be initialized by C++03 curly braces initializer, i.e., no user defined constructor:If this solution is acceptable then it’s essentially to reimplement
std::array.