How to define a static operator<<?

前端 未结 4 992
终归单人心
终归单人心 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

    What I would probably do in your situation, is create another class that overloads the operator<<, then make a static member of that type. Like this:

    class MyClass
    {
    public:
        static std::string msg;
    
        struct Out {
            Out & operator<< (const std::string& token) {
                MyClass::msg.append(token);
                return *this;
            }
        };
    
        static Out out;    
    };
    

    Using it is not quite what you asked for, but close enough I think:

    MyClass::out << "message1" << "message2";
    

提交回复
热议问题