Using gcc 4.8 with C++11 enabled, I have a class like this:
class OutStream {
public:
OutStream& operator<<(const char* s);
OutStream& operator<<(int n);
OutStream& operator<<(unsigned int n);
// ...
OutStream& vformat(const char* fmt, __VALIST args);
OutStream& format(const char* fmt, ...);
};
When I use this class by calling the operators directly, it works as I expected:
OutStream out;
out.operator<<(1).format(" formatted %04X ", 2).operator<<("3\n");
Output:
1 formatted 0002 3
Now, I'd like to got the same output but by using the <<
streaming notation, maybe like this:
OutStream out;
out << 1 << format(" formatted %04X ", 2) << "3\n";
Of course, this wouldn't compile, because there was no such operator for streaming my OutStream.format()
method.
There might be a solution where format()
was a free function which returns a string, but this needs to first write all the output of format()
into a buffer. I need a solution without std::string
or some other heap or buffer usage—at best a solution which creates nearly the same code as when calling the operators directly.
Any suggestions?
Edit, 2014-10-20:
- For better understanding my requirements: I'm on bare metal embedded development using gcc-arm-embedded gcc cross toolchain.
- I need to apply the solution for some different embedded target systems (most are Cortex-M0/M3/M4). Some of them have very limited resources (Ram & Flash) and a part of my target systems must run without any heap usage.
- For some reasons, I'm not using
Stl
iostream
. However, theiostream
tag has been set by seh edit; I'd keep it set because of thematic match and a found solution for my problem may also be applicable forStl
iostream
.