C++11:可变模板函数参数的数量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12024304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:47:14  来源:igfitidea点击:

C++11: Number of Variadic Template Function Parameters?

c++c++11variadic-templatesvariadic-functions

提问by Andrew Tomazos

How can I get a count of the number of arguments to a variadic template function?

如何获取可变参数模板函数的参数数量?

ie:

IE:

template<typename... T>
void f(const T&... t)
{
    int n = number_of_args(t);

    ...
}

What is the best way to implement number_of_argsin the above?

number_of_args在上面实施的最佳方法是什么?

回答by Nawaz

Just write this:

只写这个:

const std::size_t n = sizeof...(T); //you may use `constexpr` instead of `const`

Note that nis a constant expression (i.e known at compile-time), which means you may use it where constant expression is needed, such as:

请注意,这n是一个常量表达式(即在编译时已知),这意味着您可以在需要常量表达式的地方使用它,例如:

std::array<int,   n>  a; //array of  n elements
std::array<int, 2*n>  b; //array of (2*n) elements

auto middle = std::get<n/2>(tupleInstance);


Note that if you want to compute aggregated size of the packed types (as opposed to numberof types in the pack), then you've to do something like this:

请注意,如果您想计算打包类型的聚合大小(而不是包中的类型数量),那么您必须执行以下操作:

template<std::size_t ...>
struct add_all : std::integral_constant< std::size_t,0 > {};

template<std::size_t X, std::size_t ... Xs>
struct add_all<X,Xs...> : 
  std::integral_constant< std::size_t, X + add_all<Xs...>::value > {};

then do this:

然后这样做:

constexpr auto size = add_all< sizeof(T)... >::value;

In C++17 (and later), computing the sum of size of the types is much simpler using foldexpression:

在 C++17(及更高版本)中,使用fold表达式计算类型的大小总和要简单得多:

constexpr auto size = (sizeof(T) + ...);

Hope that helps.

希望有帮助。