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

前端 未结 7 1426
夕颜
夕颜 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:51

    Here's an alternate solution. Nothing necessarily more elegant or too fancy, but it is an alternate approach. It assumes that all classes you intend to call to_string on have a ToString() function.

    Here is a function template which will only work with objects of class type, and call a ToString() function.

        template::value>>
        std::string to_string(const T& t) {
          return t.ToString();
        }
    

    Maybe we want it to work with std::string as well.

        template<>
        std::string to_string(const std::string& t) {
          return t;
        }
    

    Here is an example of the code in use. Note the dummy namespace to_s. I guess if you put using std::to_string in the main function, it steps on our template function name, so we have to introduce the name indirectly like this. If anyone knows the correct way to do this I would appreciate a comment.

        #include 
        #include 
        #include 
        #include 
    
    
        union U {
          double d;
          const char* cp;
        };
    
        struct A {
          enum State { kString, kDouble };
          State state;
          U u;
    
          void Set(const char* cp) {
            u.cp = cp;
            state = kString;
          }
    
          std::string ToString() const {
            switch (state) {
              case A::kString : return std::string(u.cp); break;
              case A::kDouble : return std::to_string(u.d); break;
              default : return "Invalid State";
            }
          }
        };
    
        namespace to_s { using std::to_string; };
    
        int main() {
          using namespace to_s;
          std::string str = "a nice string";
          double d = 1.1;
          A a { A::kDouble, {1.2} };
    
          std::cout << "str: " << to_string(str) << ", d: " << to_string(d) << std::endl;
          std::cout << "a: " << to_string(a) << std::endl;
          a.Set(str.c_str());
          std::cout << "a: " << to_string(a) << std::endl;
          std::memset(&a, 'i', sizeof(a));
          std::cout << "a: " << to_string(a) << std::endl;
        }
    

    Here's what I got:

    str: a nice string, d: 1.100000

    a: 1.200000

    a: a nice string

    a: Invalid State

提交回复
热议问题