C++ format macro / inline ostringstream

cadabra picture cadabra · Nov 19, 2008 · Viewed 7.6k times · Source

I'm trying to write a macro that would allow me to do something like: FORMAT(a << "b" << c << d), and the result would be a string -- the same as creating an ostringstream, inserting a...d, and returning .str(). Something like:

string f(){
   ostringstream o;
   o << a << "b" << c << d;
   return o.str()
}

Essentially, FORMAT(a << "b" << c << d) == f().

First, I tried:

1: #define FORMAT(items)                                                   \
   ((std::ostringstream&)(std::ostringstream() << items)).str()

If the very first item is a C string (const char *), it will print the address of the string in hex, and the next items will print fine. If the very first item is an std::string, it will fail to compile (no matching operator <<).

This:

2: #define FORMAT(items)                                                   \
   ((std::ostringstream&)(std::ostringstream() << 0 << '\b' << items)).str()

gives what seems like the right output, but the 0 and \b are present in the string of course.

The following seems to work, but compiles with warnings (taking address of temporary):

3: #define FORMAT(items)                                                   \
   ((std::ostringstream&)(*((std::ostream*)(&std::ostringstream())) << items)).str()

Does anyone know why 1 prints the address of the c-string and fails to compile with the std::string? Aren't 1 and 3 essentially the same?

I suspect that C++0x variadic templates will make format(a, "b", c, d) possible. But is there a way to solve this now?

Answer

e.James picture e.James · Nov 19, 2008

Here is what I use. It all fits into one tidy class definition in a header file.

update: major improvement to the code thanks to litb.

// makestring.h:

class MakeString
{
    public:
        std::stringstream stream;
        operator std::string() const { return stream.str(); }

        template<class T>
        MakeString& operator<<(T const& VAR) { stream << VAR; return *this; }
};

Here is how it is used:

string myString = MakeString() << a << "b" << c << d;