If all MyClass
members are static, you can return a new instance.
However, returning the link creates a problem. There are two solutions:
- define a static instance
- transfer a copy, not a link.
The second approach is easiest:
static MyClass operator<< (MyClass, const std::string &token) { MyClass::msg.append(token); return MyClass(); }
The first is another line:
static MyClass& operator<< (MyClass&, const std::string &token) { static MyClass instance; MyClass::msg.append(token); return instance; }
Use is very close to what you want:
MyClass() << "message1" << "message2";
However, I would not recommend doing this . Why don't you just use std::ostringstream
? You will get formatting and a few more for free. If you really need global access, declare a global variable.
source share