C++ 是否可以将字符串流作为函数参数传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10833188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to pass a stringstream as a function parameter?
提问by rsk82
Is it possible to pass in a stringstream and have the function write to it directly?
是否可以传入一个字符串流并让函数直接写入它?
I remember I saw a function invoked similar to something like this:
我记得我看到过一个类似于这样的函数被调用:
my_func(ss << "text" << hex << 33);
采纳答案by eq-
Sure thing. Why wouldn't it be? Example declaration of such function:
肯定的事。为什么不会呢?此类函数的示例声明:
void my_func(std::ostringstream& ss);
回答by dasblinkenlight
Absolutely! Make sure that you pass it by reference, not by value.
绝对地!确保通过引用而不是值传递它。
void my_func(ostream& stream) {
stream << "Hello!";
}
回答by James Kanze
my_func
has to have a signature along the lines of:
my_func
必须有以下内容的签名:
void my_func( std::ostream& s );
, since that's the type of ss << "text" << hex << 33
. If the goal is
to extract the generated string, you'ld have to do something like:
,因为那是ss << "text" << hex << 33
. 如果目标是提取生成的字符串,则必须执行以下操作:
void
my_func( std::ostream& s )
{
std::string data = dynamic_cast<std::ostringstream&>(s).str();
// ...
}
Note too that you can't use a temporary stream;
另请注意,您不能使用临时流;
my_func( std::ostringstream() << "text" << hex << 33 );
won't compile (except maybe with VC++), since it's not legal C++. You could write something like:
不会编译(除了可能使用 VC++),因为它不是合法的 C++。你可以这样写:
my_func( std::ostringstream().flush() << "text" << hex << 33 );
if you wanted to use a temporary. But that's not very user friendly.
如果你想使用临时的。但这不是很用户友好。
回答by Mario Corchero
Yes it is, and
是的,而且
Function(expresion)
Will make the expression to be evaluated first and the result of it will be passed as a parameter
将首先计算表达式并将其结果作为参数传递
Note: Operator << for ostreamsreturns a ostream
注意:Ostreams 的运算符 <<返回一个 ostream