Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a static operator<<?

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 std::string msg;

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

alternatively:

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

This is how I would like to use it:

MyClass << "message1" << "message2";

Thank you!

like image 940
Pietro M Avatar asked Dec 06 '22 18:12

Pietro M


2 Answers

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";
like image 67
Benjamin Lindley Avatar answered Dec 28 '22 14:12

Benjamin Lindley


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.

like image 20
Sjoerd Avatar answered Dec 28 '22 15:12

Sjoerd