递归可变参数模板打印出参数包的内容 [英] 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 "";
}
我该如何结束递归?
推荐答案
您需要使用偏特化来结束递归,但是由于您不能在 C++ 中部分特化自由函数,您需要创建一个具有静态成员函数.
You need to use partial specialisation to end the recursion, but since you can't partially specialise free functions in C++, you need to create an implementation class with a static member function.
template <typename... Args>
struct Impl;
template <typename First, typename... Args>
struct Impl<First, Args...>
{
static std::string name()
{
return std::string(typeid(First).name()) + " " + Impl<Args...>::name();
}
};
template <>
struct Impl<>
{
static std::string name()
{
return "";
}
};
template <typename... Args>
std::string type_name()
{
return Impl<Args...>::name();
}
int main()
{
std::cout << type_name<int, bool, char, double>() << std::endl; // "i b c d"
return 0;
}
Impl
的第一个声明就是 g++ 4.6(及更低版本)中的一个缺点的解决方法.一旦正确实现了可变参数模板,就没有必要了.
That first declaration of Impl
is just a workaround for a shortcoming in g++ 4.6 (and below). It won't be necessary once it implements variadic templates correctly.
这篇关于递归可变参数模板打印出参数包的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文