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

前端 未结 7 1501
夕颜
夕颜 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:06

    First, some ADL helping:

    namespace notstd {
      namespace adl_helper {
        using std::to_string;
    
        template
        std::string as_string( T&& t ) {
          return to_string( std::forward(t) );
        }
      }
      template
      std::string to_string( T&& t ) {
        return adl_helper::as_string(std::forward(t));
      }
    }
    

    notstd::to_string(blah) will do an ADL-lookup of to_string(blah) with std::to_string in scope.

    We then modify your class:

    class my_class{
    public:
      friend std::string to_string(my_class const& self) {
        return "I am " + notstd::to_string(self.i);
      }
      int i;
    };
    

    and now notstd::to_string(my_object) finds the proper to_string, as does notstd::to_string(7).

    With a touch more work, we can even support .tostring() methods on types to be auto-detected and used.

提交回复
热议问题