可以使用临时的stringstream对象吗? [英] Can a temporary stringstream object be used?

查看:102
本文介绍了可以使用临时的stringstream对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有效:

stringstream temp;
temp << i;
result_stream << transform(temp.str());

transform 是一个需要 string 并返回 string i int )。但是,我尝试让C ++ 11创建一个没有名称的临时对象无效:

(transform is a function that takes a string and returns a string; i is an int). However, my attempt to let C++11 create a temporary object without a name didn't work:

result_stream << transform((stringstream() << i).str());

我以为它会起作用,因为第二个<< 应该只返回第一个参数,我可以在其上使用 str()。但是我得到这个错误:

I thought it would work, since the second << should just return the first argument and I'd be able to use str() on that. But I get this error:

error: 'class std::basic_ostream<char>' has no member named 'str'

我正在使用g ++ 4.8.1(MinGW-W64)。

I'm using g++ 4.8.1 (MinGW-W64).

有没有办法做到这一点(即使用未命名的临时代码编写这样的代码)? (上面的代码做了一些简化,实际代码涉及对 int 以外的参数使用<< 。)

Is there a way to accomplish this (i.e. write code like this using an unnamed temporary)? (The above code is a bit simplified, and the actual code involves using << on arguments other than int.)

推荐答案

这不起作用,因为第二个<< std :: ostream& operator<<(std :: ostream& ;, int); ,因此返回类型为 ostream& ; 没有成员 str()

This doesn't work because the second << is std::ostream &operator<<(std::ostream &, int); and so the return type is ostream& which has no member str().

您必须编写:

result_stream << transform( static_cast<stringstream &>(stringstream() << i).str() );






更新(2019):根据 LWG 1203 ,该标准将来可能会更改(并且一个主要实现已经),这样该代码将不再起作用,而可以使用更简单的代码。 详情请参阅此问题


Update (2019): According to LWG 1203 the standard may be changed in future (and one major implementation already has) so that this code no longer works, and a simpler code works instead. See this question for detail.

在过渡时期,显然,以下内容适用于新旧版本:

In the interim period, apparently the following works on both old and new:

result_stream << transform( static_cast<stringstream &>(stringstream().flush() << i).str() );
//                                                                    ^^^^^^^^

应该不会造成性能损失,因为刷新空流没有效果...

This should not be a performance penalty since flushing an empty stream has no effect...

这篇关于可以使用临时的stringstream对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆