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

前端 未结 7 1446
夕颜
夕颜 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:01

    You could define your own to_string in its own namespace (e.g., foo).

    namespace foo {
       std::string to_string(my_class const &obj) {
         return obj.string give_me_a_string_of_you();
       }
    }
    

    And use it as:

    int main(){
        my_class my_object;
        std::cout<< foo::to_string(my_object);
    }
    

    Unfortunatelly, you can't define your own version of to_string in namespace std because acorrding to the standard 17.6.4.2.1 Namespace std [namespace.std] (Emphasis Mine):

    The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

提交回复
热议问题