如何遍历递归模板类
How to traversal recursive template class
我想遍历多个深度模板类。在 C++98 中(在 C++11 之前(。
佩苏多代码。
template<typename T>
std::string find_type(T *ptr);
template <>
std::string find_type<std::string>(int *ptr)
{
return "string";
}
template <>
std::string find_type<std::list>(std::list *ptr)
{
return "list";
}
template <>
std::string find_type<std::vector>(std::vector *ptr)
{
return "vector";
}
template<T>
std::string somefunction(T *ptr)
{
if(T is template class)
return find_type + " " + somefunction(ptr);
else
return find_type(ptr);
}
我想在下面结果:
std::list<std::string> test;
somefunction(test) -> I NEED "list string";
std::list<std::vector<std::string> > test2;
somefunction(test) -> I NEED "list vector string";
我该怎么做?
我想制作模板类序列化程序。
谢谢。
我相信
这个结果不能通过模板函数专用化来实现(因为不允许部分函数专用化(。但它可以通过模板类专业化来实现:
#include <vector>
#include <list>
#include <string>
template <typename T>
struct TypePrinter;
template <typename T>
struct TypePrinter<std::vector<T> >
{
static std::string print()
{
return "vector " + TypePrinter<T>::print();
}
};
template <typename T>
struct TypePrinter<std::list<T> >
{
static std::string print()
{
return "list " + TypePrinter<T>::print();
}
};
template <>
struct TypePrinter<std::string>
{
static std::string print()
{
return "string";
}
};
int main()
{
std::string i = TypePrinter<std::list<std::string> >::print();
std::string ii = TypePrinter<std::list<std::vector<std::string> > >::print();
}
相关文章:
- 使用后序遍历递归的深度优先搜索会产生意外输出
- 递归树遍历/分支删除的隔离错误
- 递归遍历字典尝试以计算总字数
- 如何遍历递归模板类
- C++,一个通用递归模板函数,用于遍历树状结构
- 从预序遍历迭代(不是递归)构造二叉搜索树
- 这种遍历二叉树的递归方法在一些递归后崩溃!为什么?
- 使用递归的顺序二叉树遍历与使用堆栈的优缺点
- 遍历目录递归问题
- 使用递归的顺序和预序遍历 - 二叉搜索树 C++
- 递归后序遍历解除分配二叉树节点
- 使用 QDirIterator 递归遍历目录
- 如何实现非递归 inOrder 遍历
- 无法使用非递归顺序方法遍历二叉树
- 递归二进制树遍历代码走向无穷大
- 使用递归函数对XML树进行预序遍历
- 递归:按顺序遍历返回列表
- 使用递归的BST顺序遍历
- 下面使用Map和Vector实现递归级阶遍历的时间复杂度是多少
- 是否可以使用迭代而不是递归来遍历二叉树?