开发者

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 t开发者_如何学Gohe 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:

  • you can turn the hard-error into a soft-error by using std::enable_if (triggering SFINAE); I wouldn't recommend it
  • you can change the condition to be sizeof...(U) <= Size, letting the remaining elements to be value initialized
  • you can require that the types passed to the constructor are convertible to T, or exactly match e.g. T const&; either turning a violation into a hard-error (using static_assert again) or a soft-error (SFINAE again)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜