Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to make a variadic template with exactly N arguments, where N is also a template parameter. For example,

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

(I realize the above is not valid syntax)

I know that one way to achieve this is to use a static_assert on sizeof...(ArgsT) where ArgsT is a variadic template definition (i.e. template <typename ...ArgsT>).

I am just wondering if there is a better way, not necessarily involving static_assert.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use std::enable_if instead of static_assert:

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

Update: It's also possible to use it in constructors, where N is a template argument of the class.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...