Making a user-defined class std::to_string(able)

前端 未结 7 1548
夕颜
夕颜 2021-02-01 02:23

I know it seems too much Java or C#. However, is it possible/good/wise to make my own class valid as an input for the function std::to_string ? Example:

<         


        
7条回答
  •  名媛妹妹
    2021-02-01 02:59

    This already has a great answer but I'd like to propose an alternative, feedback is welcome.

    If you're not dead set on the to_string function name, you could implement your own ToString free function template, with specializations for the types supported by to_string:

    template
    std::string ToString(const T& t)
    {
        std::ostringstream stream;
        const uint8_t* pointer = &t;
        for(size_t i=0;i std::string ToString(const int& t) { return std::to_string(t); }
    template<> std::string ToString(const long& t) { return std::to_string(t); }
    template<> std::string ToString(const long long& t) { return std::to_string(t); }
    template<> std::string ToString(const unsigned& t) { return std::to_string(t); }
    template<> std::string ToString(const unsigned long& t) { return std::to_string(t); }
    template<> std::string ToString(const unsigned long long& t) { return std::to_string(t); }
    template<> std::string ToString(const float& t) { return std::to_string(t); }
    template<> std::string ToString(const double& t) { return std::to_string(t); }
    

    The default implementation here returns a string of hex values with the values at the memory space for the class reference passed, while the specializations call std::to_string, this will make any class "stringable".

    Then you just need to implement your own specialization for your class:

    template<> std::string ToString(const my_class& t) { return "I am " + std::to_string(t.i); }
    

提交回复
热议问题