【问题标题】:How to traversal recursive template class如何遍历递归模板类
【发布时间】:2019-04-08 05:45:12
【问题描述】:

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

我该怎么做?

我想做模板类序列化器。

谢谢。

【问题讨论】:

    标签: c++ templates c++98


    【解决方案1】:

    我相信这个结果不能通过模板函数特化来实现(因为不允许部分函数特化)。但它可以通过模板类特化来实现:

    #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();
    }
    

    【讨论】:

    • +1。虽然这是一个小错误,TypePrinter&lt;std::vector&lt;T&gt;&gt;::print 应该打印 "vector",而不是 "string" :)
    猜你喜欢
    • 1970-01-01
    • 2018-07-12
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多