Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

C++ format macro / inline ostringstream

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 << '' << items)).str()

gives what seems like the right output, but the 0 and 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...