C++ 字符串流内联 [英] C++ stringstream inline
问题描述
我想使用 std::stringstream
来创建格式化的字符串,但使用内联类,所以我没有 stringstream
局部变量四处乱飞.我的意思是:
I would like to use std::stringstream
to create formatted strings, but use the class inline so I don't have stringstream
local variables flying around. What I mean is this:
#include <iostream>
#include <ostream>
#include <string>
#include <sstream>
int main(int argc, char* argv[])
{
std::string test = ((std::ostringstream&)
(std::ostringstream("") << "This is a test: " << 50.1 << "abc")
).str();
std::cout << test << std::endl;
return 0;
}
这在 GCC 中编译得很好,但是输出如下:
This compiles fine in GCC, however the output is the following:
"0x401d0a50.1abc"
"0x401d0a50.1abc"
所以看起来stringstream
把第一个字符串当成一个指针,输出地址.后续 operator<<
的工作正常.
So it seems that stringstream
treats the first string as a pointer and outputs the address. Subsequent operator<<
's work fine.
我该如何解决这个问题?谢谢!
How do I fix this? Thanks!
推荐答案
原因是 <<
运算符是 void const*
的成员,但是一个自由函数,将 std::ostream&
作为 char const*
的左侧参数.你的 std::ostringstream( "" )
是一个临时的:你可以在它上面调用成员函数(甚至非常量成员函数),但临时不能用于初始化非常量引用全局函数.
The reason is that the <<
operator is a member for void const*
, but a free function taking an std::ostream&
as the left hand argument for char const*
. Your std::ostringstream( "" )
is a temporary: you can call member functions (even non-const member functions) on it, but a temporary cannot be used to initialize the non-const reference of the global function.
两点:首先,正如已经指出的,g++ 确实做你想做的事如果您指定 -std=c++11
,则需要.作为 T.C.指出,这是在 §27.7.3.9 中指定,它为所有 <<
带有 std::istream
的右值引用范围.其次,经典的解决方法是开始表达式 std::ostringstream( "" ).flush() <<...
.flush
是一个成员函数(因此可以在一个临时的),它返回一个 std::ostream&
(所以一切否则很好地链接);它也没有任何作用一个 std::ostringstream
.
Two points: first, as has been pointed out, g++ does do what you
want if you specify -std=c++11
. As T.C. points out, this is
specified in §27.7.3.9, which provides a template overload for
all <<
with an rvalue reference for the std::istream
parameter.
And second, the classic work around is
to start the expression std::ostringstream( "" ).flush() <<...
. flush
is a member function (and so can be called on
a temporary) which returns an std::ostream&
(so everything
else chains nicely); it also does nothing on
a std::ostringstream
.
这篇关于C++ 字符串流内联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!