【发布时间】:2014-12-03 07:36:12
【问题描述】:
我一直在寻找解决方案,但找不到我需要/想要的。
我想要做的就是将一个用于 std::cout 的流传递给一个函数,该函数对其进行操作。到目前为止我使用的是一个模板函数:
template<typename T>
void printUpdate(T a){
std::cout << "blabla" << a << std::flush;
}
int main( int argc, char** argv ){
std::stringstream str;
str << " hello " << 1 + 4 << " goodbye";
printUpdate<>( str.str() );
return 0;
}
我更喜欢这样的:
printUpdate << " hello " << 1 + 4 << " goodbye";
或
std::cout << printUpdate << " hello " << 1 + 4 << " goodbye";
我想这样做:
void printUpdate(std::istream& a){
std::cout << "blabla" << a << std::flush;
}
但这给了我:
error: invalid operands of types ‘void(std::istream&) {aka void(std::basic_istream<char>&)}’ and ‘const char [5]’ to binary ‘operator<<’
【问题讨论】:
-
您不能将数据输出到输入流。将参数更改为
std::ostream& a。此外,flush没有为输入流定义。 -
我也试过了。相同的错误:错误:'void(std::ostream&) {aka void(std::basic_ostream
&)}'和'const char [5]'类型的无效操作数到二进制'operator -
在您的
main函数中,您需要为printUpdate函数调用提供流类型,例如printUpdate<std::ostream>。 -
不知道你到底想要什么。但是如果你想做任何看起来像
printUpdate() << "this is my output"的事情(注意括号),你必须从printUpdate()返回流。如果您想在将其推送到std::cout之前对右侧做一些花哨的事情,或者您想在您的内容之后将某些内容推送到 std::cout(如 printUpdate 的内容所建议的那样), printUpdate 应该是一个类一个重载的template <typename T> operator<<(T data)。然后你可以将printUpdate << "Bla"翻译成std::cout << X << "Bla" << Y,其中X和Y是固定的。 -
@Oguk 谢谢,所以可能没有比让 printUpdate 成为一个类更简单的替代方法了。