使用匿名Stringstream构造一个字符串 [英] Use an Anonymous Stringstream to Construct a String
问题描述
我想直接读入一个字符串,如下所示:
I want to read directly into a string with code like this:
std::string myString(( std::ostringstream() << myInt << " "
<< myFloat << " "
<< std::boolalpha << myBool ).str());
但VS2012让我抱怨 basic_ostream
没有 str()
方法。
But VS2012 is giving me a complaint that basic_ostream
doesn't have an str()
method.
有一种方法可以用匿名stringstream ?运算符<<
对于流返回<$ c>
Is there a way to do this with an anonymous stringstream?
推荐答案
$ c> std :: ostream& ,它没有 str()
成员函数。您需要使用cast。
The operator<<
for streams returns std::ostream &
which doesn't have str()
member function. You need to use cast.
static_cast<std::ostringstream&>(std::ostringstream() << etc).str()
+03和C ++ 11使用临时流!
C ++ 03
在C ++ 03中) std :: ostringstream()
创建一个临时对象,这意味着<$ c $的非成员重载 不能为第一个
运算符,因为它们都接受第一个参数 std :: ostream&
,它不能绑定到临时对象。临时对象将能够调用只有成员函数。
Differences between C++03 and C++11 when using temporary stream!
C++03
But be aware (in C++03) that std::ostringstream()
creates a temporary object, which means the non-member overloads of operator<<
cannot be invoked for the first <<
because all of them accepts the first argument as std::ostream&
which cannot bind to the temporary object. The temporary object will be able to invoke only member functions.
这意味着,而不是 string :
static_cast<std::ostringstream&>(std::ostringstream() << "XYZ").str()
$ c> char const * 作为参数是一个非成员函数,不能被调用,所以上面的代码最后调用成员函数 void const *
作为参数,因此XYZ
隐式转换为 void const *
,它打印字符串文字的地址。
Because the overload which takes char const*
as argument is a non-member function, which cannnot be invoked, so the above code end up calling the member function which takes void const*
as argument and thus "XYZ"
is implicitly converted into void const*
, which prints address of string literal.
一旦临时调用成员函数,剩余的链接 ;
可调用非成员重载,因为成员函数返回 std :: ostream&
其中现在可以绑定到运算符的非成员重载的第一个参数
。因此,以下代码将打印地址(而不是XYZ
),后跟字符串ABC
:
Once the temporary invokes the member function, the remaining chained <<
may invoke non-member overloads, because the member function return std::ostream&
which now can bind to the first argument to the non-member overloads of operator<<
. So this following code would print an address (instead of "XYZ"
) followed by string "ABC"
:
static_cast<std::ostringstream&>(std::ostringstream() << "XYZ" << "ABC").str()
在线演示:
- GCC output without
-std=c++11
- Clang output without
-std=c++11
在C ++ 11中,此问题已通过添加非成员函数(27.7.3.9),它将第一个参数作为右值引用,然后将该调用转发到适当的函数(成员或非成员)。因此,它打印 XYZ
后跟 ABC
:
In C++11, this issue has been fixed by adding a non-member function (27.7.3.9) which takes the first argument as rvalue reference which then forwards the call to the appropriate function, either member or non-member. So it prints XYZ
followed by ABC
:
- GCC output with
-std=c++11
- Clang output with
-std=c++11
这篇关于使用匿名Stringstream构造一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!