Inline ostringstream macro reloaded

感情迁移 提交于 2019-12-08 04:52:58

问题


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...?


回答1:


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.



来源:https://stackoverflow.com/questions/492475/inline-ostringstream-macro-reloaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!