Template specialisation where templated type is also a template

前端 未结 2 2024
既然无缘
既然无缘 2021-01-05 20:43

I\'ve created a small utility function for string conversion so that I don\'t have to go around creating ostringstream objects all over the place

template<         


        
2条回答
  •  一个人的身影
    2021-01-05 21:07

    What about using type traits for serializing different types to the stream like this:

    template
    struct Traits {
      static inline bool ToStream(std::ostringstream& o, const T& x) {
        return o << x;
      }
    };
    
    template
    struct Traits > {
      static inline bool ToStream(std::ostringstream& o, const std::pair& x) {
        return o << "[" << x.first << "," << x.second << "]";
      }
    };
    
    template
    inline std::string ToString(const T& x)
    {
      std::ostringstream o;
      if (!Traits::ToStream(o, x))
        return "Error";
      return o.str();
    }
    

    Note: "template<>" from the specialization part is optional, the code compiles fine without it. You can further add methods in the traits for the exception message.

提交回复
热议问题