Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...>();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...