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