简体   繁体   中英

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.

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>>;

Probably the simplest way is just to use static_assert . Add pattern matching as appropriate:

template<int N, typename... Args>
void foo(Args... args) {
    static_assert(sizeof...(args) == N, "Incorrect number of arguments");
    // stuff
}

This will do most of the time, even allowing you to have a nice friendly custom error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM