c++11 - C++ Templates variadic but static -
i training template skills in c++ , want implement vector class. class defined vector dimension n , type t. have constructor takes n variables of type t. can't head around how tell variadic template accept n parameters. maybe possible template specialization? or thinking in wrong direction? thoughts/ideas on appreciated.
more thoughts
all examples on variadic templates saw used recursion "iterate" through parameter list. have in mind constructors can not called constructors (read comments in answer). maybe not possible use variadic templates in constructors? anyway defer me usage of factory function 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 static_assert
generate hard-error if not size
arguments passed constructor. can tweaked:
- you can turn hard-error soft-error using
std::enable_if
(triggering sfinae); wouldn't recommend it - you can change condition
sizeof...(u) <= size
, letting remaining elements value initialized - you can require types passed constructor convertible
t
, or match e.g.t const&
; either turning violation hard-error (usingstatic_assert
again) or soft-error (sfinae again)
Comments
Post a Comment