Search code examples
c++visual-c++macrosostringstream

Inline ostringstream macro reloaded


Referring to C++ format macro / inline ostringstream

The question there was for a macro that allows inline concatenation of objects to create a string, iostream-style.

The answer was:

#define SSTR( x ) dynamic_cast< std::ostringstream & >( \
        ( std::ostringstream().seekp( 0, std::ios_base::cur ) << x ) \
    ).str()

Usage (for example):

throw std::runtime_error(
        SSTR( "FooBar error: Value " << x << " exceeds " << y )
);

That works beautifully - with GCC. It compiles and runs under Visual C++ 2005, too. But with the latter, all uses of the macro result in empty strings, and I am quite dumbfounded as to why, and how to fix it...?


Solution

  • Unfortunately I don't have access to a MSVC compiler to test against.

    In my past experiences with microsoft's tools, it seems like microsoft treats language definitions and standards as little more than a rough guide. (I've lost lots of time on projects only to discover microsoft broke tradition with something as basic as C99.)

    Given this regrettably situation, I suggest you experiment with a series of trivial programs. Things like:

    std::ostringstream() o;
    o.seekp( 0, std::ios_base::cur ) << "foo";
    cout << "Test1:  " << o << endl;
    

    Or perhaps:

    std::ostringstream() o;
    cout << "Test2:  " << typeid(o).name() << endl;
    cout << "Test3:  " << typeid(o.seekp( 0, std::ios_base::cur )).name() << endl;
    

    Try to see at what point things stop working. Then work around the problem from there.