如何遍历递归模板类

How to traversal recursive template class

本文关键字:递归 遍历 何遍历      更新时间:2023-10-16

我想遍历多个深度模板类。在 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();
}