recursive variadic template to print out the contents of a parameter pack

Gabor Marton picture Gabor Marton · Aug 19, 2011 · Viewed 20.3k times · Source

How is it possible to create a recursive variadic template to print out the contents of a paramater pack? I am trying with this, but it fails to compile:

template <typename First, typename ...Args>
std::string type_name () {
    return std::string(typeid(First).name()) + " " + type_name<Args...>();
}
std::string type_name () {
    return "";
}

How shall I end the recursion?

Answer

Aberrant picture Aberrant · Jul 11, 2015

There's actually a very elegant way to end the recursion:

template <typename Last>
std::string type_name () {
    return std::string(typeid(Last).name());
}

template <typename First, typename Second, typename ...Rest>
std::string type_name () {
    return std::string(typeid(First).name()) + " " + type_name<Second, Rest...>();
}

I initially tried template <typename Last> and template <typename First, typename ...Rest> but that was considered ambiguous (Rest can be zero elements). This question then showed me the definitive solution: Compilation Error on Recursive Variadic Template Function


Note, to avoid a bit of code duplication, you could also do:

template <typename Last>
std::string type_name () {
    return std::string(typeid(Last).name());
}

template <typename First, typename Second, typename ...Rest>
std::string type_name () {
    return type_name<First>() + " " + type_name<Second, Rest...>();
}