Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 373
Eternal Learner Avatar asked May 05 '10 03:05

Eternal Learner


People also ask

What is parameter pack in c++?

Parameter packs (C++11) A parameter pack can be a type of parameter for templates. Unlike previous parameters, which can only bind to a single argument, a parameter pack can pack multiple parameters into a single parameter by placing an ellipsis to the left of the parameter name.

What is a variadic template c++?

Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue.

What is Pack expansion?

Pack expansion A pattern followed by an ellipsis, in which the name of at least one parameter pack appears at least once, is expanded into zero or more comma-separated instantiations of the pattern, where the name of the parameter pack is replaced by each of the elements from the pack, in order. template<class...


1 Answers

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.

like image 192
GManNickG Avatar answered Sep 20 '22 21:09

GManNickG