C ++ 11:可变参数模板函数参数的数量? [英] C++11: Number of Variadic Template Function Parameters?

查看:129
本文介绍了C ++ 11:可变参数模板函数参数的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

即:

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

    ...
}

最好的方法是什么在上面实现 number_of_args

What is the best way to implement number_of_args in the above?

推荐答案

只需编写以下内容:

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

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

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

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);






请注意,如果要计算打包的类型(而不是打包中的类型的 number ),则必须执行以下操作:


Note that if you want to compute aggregated size of the packed types (as opposed to number of 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 > {};

然后执行以下操作:

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

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

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

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

希望有帮助。

这篇关于C ++ 11:可变参数模板函数参数的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆