问题
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 ?
回答1:
Use sizeof...
:
template<typename... Args>
constexpr std::size_t length(Args...)
{
return sizeof...(Args);
}
Note you shouldn't be using unsigned
, but std::size_t
(defined in <cstddef>
). Also, the function should be a constant expression.
Without using 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
}
Note, everything is completely untested.
来源:https://stackoverflow.com/questions/2770474/how-to-find-the-length-of-a-parameter-pack