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...>();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…