How to define a static operator<<?

前端 未结 4 961
终归单人心
终归单人心 2021-01-03 06:37

Is it possible to define a static insertion operator which operates on the static members of a class only? Something like:

class MyClass
{
public:
    static         


        
4条回答
  •  心在旅途
    2021-01-03 07:17

    If all the members of MyClass are static, it's possible to return a fresh instance.

    However, returning a reference poses a problem. There are two solutions:

    • define a static instance
    • pass by copy, and not by reference.

    The second approach is easiest:

    static MyClass operator<< (MyClass, const std::string &token)
    {
         MyClass::msg.append(token);
         return MyClass();
    }
    

    The first is one line more:

    static MyClass& operator<< (MyClass&, const std::string &token)
    {
         static MyClass instance;
    
         MyClass::msg.append(token);
         return instance;
    }
    

    Usage is very close to what you want:

    MyClass() << "message1" << "message2";
    

    However, I would not recommend to do this. Why don't you just just use a std::ostringstream? You'll get formatting and some more for free. If you really need global access, declare a global variable.

提交回复
热议问题