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

前端 未结 7 1520
夕颜
夕颜 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:50

    What's the 'best' way is an open question.

    There are a few ways.

    The first thing to say is that overloading std::to_string for a custom type is not allowed. We may only specialise template functions and classes in the std namespace for custom types, and std::to_string is not a template function.

    That said, a good way to treat to_string is much like an operator or an implementation of swap. i.e. allow argument-dependent-lookup to do the work.

    so when we want to convert something to a string we could write:

    using std::to_string;
    auto s = to_string(x) + " : " + to_string(i);
    

    assuming that x was an object of type X in namespace Y and i was an int, we could then define:

    namespace Y {
    
      std::string to_string(const X& x);
    
    }
    

    which would now mean that:

    invoking to_string(x) actually selects Y::to_string(const Y::X&), and

    invoking to_string(i) selects std::to_string(int)

    Going further, it may be that you want to_string to do much the same as operator<<, so then one can be written in terms of the other:

    namespace Y {
    
      inline std::ostream& operator<<(std::ostream& os, const X& x) { /* implement here */; return os; }
    
      inline std::string to_string(const X& x) {
        std::ostringstream ss;
        ss << x;
        return ss.str();
      }
    }
    

提交回复
热议问题