I am training my template skills in C++ and want to implement a vector class.
The class is defined by the vector dimension N and the type T.
Now I would like to have a constructor that takes exactly N variables of type T.
However I can’t get my head around how to tell the variadic template to only accept N parameters. Maybe this is possible with template specialization?
Or am I thinking in the wrong direction?
Any thoughts/ideas on this would be greatly appreciated.
More thoughts
All examples on variadic templates I already saw used recursion to “iterate” through the parameter list. However I have in mind that constructors can not be called from constructors (read the comments in the answer). So maybe it is not even possible to use variadic templates in constructors? Anyway that would only defer me to the usage of a factory function with the same basic problem.
A variadic constructor seems appropriate:
This example uses perfect forwarding and and
static_assertto generate a hard-error if not exactlySizearguments are passed to the constructor. This can be tweaked:std::enable_if(triggering SFINAE); I wouldn’t recommend itsizeof...(U) <= Size, letting the remaining elements to be value initializedT, or exactly match e.g.T const&; either turning a violation into a hard-error (usingstatic_assertagain) or a soft-error (SFINAE again)