Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c++ - Variadic templates with exactly n parameters

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) { ... }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...