Variadic templates with exactly n parameters

I want to create a variation template with exactly N arguments, where N is also a template parameter. For instance,

template <int N, typename T[N]>
void function(T t[N]) {
    // do stuff with t[0] through t[N-1]
}

(I understand that the above syntax is invalid)

I know that one way to achieve this is to use static_asserton sizeof...(ArgsT), where ArgsTis the definition of the variational pattern (i.e. template <typename ...ArgsT>).

I'm just wondering if there is a better way, not necessarily including static_assert.

+1
source share
1 answer

You can use std::enable_ifinstead static_assert:

template <std::size_t N, typename ...Args>
auto function(Args&&... args)
    -> typename std::enable_if<N == sizeof...(Args), void>::type
{
    ...
}

: , N .

template <std::size_t N>
struct foobar
{
    template <typename ...Args, typename = typename std::enable_if<N == sizeof...(Args), void>::type>
    foobar(Args&&... args) { ... }
};
+7

All Articles