Suppose I have a variadic template function like
template
unsigned length(Args... args);
How do I find the length o
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.