Search code examples
c++templates

Is there any way for a C++ template function to take exactly N arguments?


What I mean is, for example, a constructor for a class like the following:

class vector<size_t N, typename FLOAT=double> {
    vector(FLOAT ...x) {} // I want exactly N arguments here
};

I hope it's clear that I do not want a variadic function, but a function that takes exactly N arguments, when N is known at compile-time. Thus, using the example above, vector<3>(1.5, 2.5) should produce a compile-time error, while vector<2>(1.5, 2.5) should compile and run.

Is this possible?

I was thinking that perhaps this could be done with parameter packs, but I'm not quite sure how.


Solution

  • With some indirection, you may do something like:

    template <std::size_t, typename T> using alwaysT = T;
    
    template <typename FLOAT, typename Seq> struct vector_impl;
    
    template <typename FLOAT, std::size_t... Is>
    struct vector_impl<FLOAT, std::index_sequence<Is...>> {
         vector_impl(alwaysT<Is, FLOAT>... floats) { /*...*/}
    };
    
    template <std::size_t N, typename FLOAT>
    using vector = vector_impl<FLOAT, std::make_index_sequence<N>>;