如何遍历递归模板类

时间:2019-04-08 05:45:13

标签: c++ templates c++98

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

我该怎么办?

我要制作模板类序列化器。

谢谢。

1 个答案:

答案 0 :(得分:3)

我认为不能通过模板功能专门化来实现此结果(因为不允许部分函数专门化)。但这可以通过模板类专门化来实现:

#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();
}
相关问题