C++ Templates variadic but static
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:
template<typename T, int Size>
struct vector {
template<typename... U>
explicit
vector(U&&... u)
: data {{ std::forward<U>(u)... }}
{
static_assert( sizeof...(U) == Size, "Wrong number of arguments provided" );
}
T data[Size];
};
This example uses perfect forwarding and and static_assert
to generate a hard-error if not exactly Size
arguments are passed to the constructor. This can be tweaked:
std::enable_if
(triggering SFINAE); I wouldn't recommend it sizeof...(U) <= Size
, letting the remaining elements to be value initialized T
, or exactly match eg T const&
; either turning a violation into a hard-error (using static_assert
again) or a soft-error (SFINAE again) 上一篇: Variadic模板候选人无与伦比
下一篇: C ++模板variadic但静态