【发布时间】:2010-05-05 03:45:20
【问题描述】:
假设我有一个可变参数模板函数,比如
template<typename... Args>
unsigned length(Args... args);
如何使用长度函数找到参数列表的长度?
【问题讨论】:
标签: c++ templates c++11 variadic-functions variadic
假设我有一个可变参数模板函数,比如
template<typename... Args>
unsigned length(Args... args);
如何使用长度函数找到参数列表的长度?
【问题讨论】:
标签: c++ templates c++11 variadic-functions variadic
使用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
}
注意,一切都完全未经测试。
【讨论】: