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

前端 未结 7 1428
夕颜
夕颜 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 03:10

    You can't add new overloads of to_string into std namespace, but you can do it in your namespace:

    namespace my {
       using std::to_string;
    
       std::string to_string(const my_class& o) {
         return o.give_me_a_string_of_you();
       }
    }
    

    Then you can use my::to_string for all types.

    int main()
    {
        my_class my_object;
    
        std::cout << my::to_string(my_object);
        std::cout << my::to_string(5);
    }
    
    0 讨论(0)
提交回复
热议问题