Is specialization of std::to_string for custom types allowed by the C++ standard?

后端 未结 4 1561
情话喂你
情话喂你 2020-12-16 09:29

In C++11 and later, is it allowed to specialize std::to_string in the std namespace for custom types?

namespace std {
string to_str         


        
4条回答
  •  误落风尘
    2020-12-16 10:02

    Better way would be to create your own function that make use of std::to_string if it's possible as well as the .toString() method whenever it's available for passed argument:

    #include 
    #include 
    #include 
    
    struct MyClass {
       std::string toString() const { return "MyClass"; }
    };
    
    template
    typename std::enable_if().toString()), std::string>::value, std::string>::type my_to_string(const T &t) {
        return t.toString();
    }
    
    template
    typename std::enable_if())), std::string>::value, std::string>::type my_to_string(const T &t) {
        return std::to_string(t);
    }
    
    int main() {
       std::cout << my_to_string(MyClass()) << std::endl; // will invoke .toString
       std::cout << my_to_string(1) << std::endl; //will invoke std::to_string
    }
    

提交回复
热议问题