Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 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?

question from:https://stackoverflow.com/questions/7124969/recursive-variadic-template-to-print-out-the-contents-of-a-parameter-pack

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

1 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...