假设我有一个像这样的可变参数模板函数
template<typename... Args>
unsigned length(Args... args);
如何使用长度函数找到参数列表的长度?
最佳答案
使用 sizeof...
:
template<typename... Args>
constexpr std::size_t length(Args...)
{
return sizeof...(Args);
}
注意你不应该使用 unsigned
,但是std::size_t
(在 <cstddef>
中定义)。此外,该函数应该是一个常量表达式。
不使用 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
}
请注意,一切都完全未经测试。
关于c++ - 如何找到参数包的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2770474/