[英]C++ function that returns an ostream
我有许多operator<<()
函数,它们从做类似的事情开始,所以我想抽象一下。 这是我正在尝试做的最小可重复案例(消除了所有复杂性)。 请注意,它不会编译。 如果它确实编译了,我希望程序自己在一行上打印数字 3。
/*
clang++ -std=c++14 -Wall -Wextra foo.cc -o foo
*/
#include <ostream>
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
ostream& BaseFunction(ostream& os, const int x) {
return os << x;
}
int main(int argc, char *argv[]) {
cout << BaseFunction(cout, 3) << endl;
}
错误是这样开始的:
foo.cc:17:8: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and
'ostream')
cout << BaseFunction(cout, 3) << endl;
~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~
然后提供大量“从 ostream 到 T 的未知转换”建议。
有人看到我做错了什么吗?
Basefunction(cout, 3)
返回cout
。
因此,最后一行相当于
cout << 3;
cout << cout << endl;
由于cout << cout
没有意义,你会得到一个错误。
你为此使用了一种非常奇怪和独特(即糟糕)的模式,使用它的方法是:
BaseFunction(cout, 3) << endl;
Note that you pass your input stream to your function as a parameter, and since you return the stream as an output, and there is no overload of operator<<
that takes a stream on the left and right sides at the same time, the regular使用 C++ 流的方式在这里不起作用。
完成此操作的通常方法是添加一个operator<<
重载,该重载采用左侧 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 和右侧自定义 object ,并执行您需要执行的任何操作来显示您的 ZA8CFDE6331BD59EB2AC96F8911C4B666。 在您的情况下,将 function 替换为不将 stream 作为参数并返回自定义 object 然后您可以使用它来重载流式操作符。
您所做的实际上是定义一个自定义 stream 操纵器。 可以改为这样实现:
/* clang++ -std=c++14 -Wall -Wextra foo.cc -o foo */
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
struct myValue {
int value;
};
myValue BaseFunction(const int x) {
return myValue{x};
}
ostream& operator<<(ostream &os, const myValue &v) {
return os << v.value;
}
int main(int argc, char *argv[]) {
cout << BaseFunction(3) << endl;
}
你可以试试这个:
BaseFunction(cout, 3);
cout << endl;
我认为 ostream 不能 output 一个ostream。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.