C++11: Number of Variadic Template Function Parameters?

Viewed 43211

How can I get a count of the number of arguments to a variadic template function?

ie:

template<typename... T>
void f(const T&... t)
{
    int n = number_of_args(t);

    ...
}

What is the best way to implement number_of_args in the above?

2 Answers
#include <iostream>

template<typename ...Args>
struct SomeStruct
{
    static const int size = sizeof...(Args);
};

template<typename... T>
void f(const T&... t)
{
    // this is first way to get the number of arguments
    constexpr auto size = sizeof...(T);
    std::cout<<size <<std::endl;
}

int main ()
{
    f("Raje", 2, 4, "ASH");
    // this is 2nd way to get the number of arguments
    std::cout<<SomeStruct<int, std::string>::size<<std::endl;
    return 0;
}
Related