具有正好n个参数的变化模板 [英] Variadic templates with exactly n parameters
问题描述
我想制作一个具有完全N个参数的可变参数模板,其中N也是一个模板参数。例如,
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)
我知道一种方法来实现这是使用 static_assert
在 sizeof ...(ArgsT)
其中 ArgsT
是可变参数模板定义(即
template< typename ... ArgsT>
)。
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>
).
我只是想知道是否有更好的方法,不一定涉及 static_assert
。
I am just wondering if there is a better way, not necessarily involving static_assert
.
推荐答案
您可以使用 std :: enable_if
,而不是 static_assert
:
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
{
...
}
更新:也可以在构造函数中使用, N
是该类的模板参数。
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) { ... }
};
这篇关于具有正好n个参数的变化模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!