递归可变参数模板以打印出参数包的内容 [英] 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;
}
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屋!
查看全文