如何找到参数包的长度? [英] How to find the length of a parameter pack?
本文介绍了如何找到参数包的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个可变参数模板函数,例如
Suppose I have a variadic template function like
template<typename... Args>
unsigned length(Args... args);
如何使用长度函数查找参数列表的长度?
How do I find the length of the parameter list using the length function ?
推荐答案
使用 sizeof ...
:
template<typename... Args>
constexpr std::size_t length(Args...)
{
return sizeof...(Args);
}
请注意,您不应该使用未签名的
,但 std :: size_t
(在< cstddef>
中定义)。此外,该函数应该是一个常量表达式。
Note you shouldn't be using unsigned
, but std::size_t
(defined in <cstddef>
). Also, the function should be a constant expression.
不使用 sizeof ...
:
namespace detail
{
template<typename T>
constexpr std::size_t length(void)
{
return 1; // length of 1 element
}
template<typename T, typename... Args>
constexpr std::size_t length(void)
{
return 1 + length<Args...>(); // length of one element + rest
}
}
template<typename... Args>
constexpr std::size_t length(Args...)
{
return detail::length<Args...>(); // length of all elements
}
注意,所有内容都未经测试。
这篇关于如何找到参数包的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文