重新加载内联 ostringstream 宏

发布于 2024-07-13 08:00:18 字数 625 浏览 5 评论 0原文

参考 C++ 格式宏/​​内联 ostringstream

问题是允许内联的宏连接对象以创建字符串,iostream 样式。

答案是:

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

用法(例如):

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

与 GCC 配合使用效果非常好。 它也在 Visual C++ 2005 下编译和运行。 但对于后者,宏的所有使用都会导致空字符串,我对为什么以及如何修复它感到非常困惑......?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

血之狂魔 2024-07-20 08:00:18

不幸的是我无法访问 MSVC 编译器来进行测试。

根据我过去使用微软工具的经验,微软似乎将语言定义和标准视为粗略的指南。 (我在项目上浪费了很多时间,却发现微软用像 C99 这样基本的东西打破了传统。)

鉴于这种令人遗憾的情况,我建议您尝试一系列琐碎的程序。 例如:

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

或者也许:

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

尝试看看什么时候事情停止工作。 然后从那里解决问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文