Search code examples
c++variadic-templates

Get number of 'nested' template arguments of a template type in c++


How can I get the number of 'nested' template arguments of a type in c++?

I would like to write a function GetNumberOfTypes<T>() that returns the number of template arguments of T:

constexpr int a = GetNumberOfTypes<int>(); //a == 0
constexpr int b = GetNumberOfTypes<std::vector<int>>(); //b == 1
constexpr int c = GetNumberOfTypes<std::tuple<int,int>>(); //c == 2

Can this be accomplished somehow? I've messed around with sizeof..., but I don't really know what I'm doing...


Solution

  • You might (somehow) do it with specialization:

    template <typename T>
    struct TemplateArity : std::integral_constant<std::size_t, 0>
    {};
    
    template <template <typename...> class C, typename ...Ts>
    struct TemplateArity<C<Ts...>> : std::integral_constant<std::size_t, sizeof...(Ts)>
    {};
    

    Demo

    We cannot mix in generic way types, non-type and template-template parameters, so std::array is not handled for example.