Variable number of constructor parameters depending on integer template

后端 未结 3 989
感动是毒
感动是毒 2021-01-03 02:51

I\'m writing a container storage class template that wraps a private std::array in order to add some functionality to it. The template parametrises the number o

相关标签:
3条回答
  • 2021-01-03 03:14

    By following Member function template with the number of parameters depending on an integral template parameter and Variadic templates with exactly n parameters, have got it working with the following code.

    template<size_t N> class Vector {
    private:
        array<double, N> vals;
    public:
        template <typename ...T,
              typename enable_if<sizeof...(T) == N, int>::type = 0>
        Vector(T ...args) : vals{args} {}
    };
    
    0 讨论(0)
  • 2021-01-03 03:19

    Don't get what you mean by this:

    Variadic arguments don't provide a mechanism to check how many of them there are, so they're right out

    template <typename ...T>
    Vector(T... args) {
        static_assert(sizeof...(args) <= N, "oops");
    }
    

    Should work..

    0 讨论(0)
  • 2021-01-03 03:22

    You could additionally generate a pack of the right size via some template specialization tricks:

    template <size_t N, class = std::make_index_sequence<N>>
    class Vector;
    
    template <size_t N, size_t... Is>
    class Vector<N, std::index_sequence<Is...>> 
    {
    private:
        std::array<double, N> vals;
    
        template <size_t >
        using double_ = double;
    public:
        Vector(double_<Is>... vals)
        {
            ...
        }
    };
    

    That is a non-template constructor which takes N doubles.

    0 讨论(0)
提交回复
热议问题