运算符<<无法输出 std::endl -- 修复吗?
以下代码在应该仅输出 std::endl
时给出错误:
#include <iostream>
#include <sstream>
struct MyStream {
std::ostream* out_;
MyStream(std::ostream* out) : out_(out) {}
std::ostream& operator<<(const std::string& s) {
(*out_) << s;
return *out_;
}
};
template<class OutputStream>
struct Foo {
OutputStream* out_;
Foo(OutputStream* out) : out_(out) {}
void test() {
(*out_) << "OK" << std::endl;
(*out_) << std::endl; // ERROR
}
};
int main(int argc, char** argv){
MyStream out(&std::cout);
Foo<MyStream> foo(&out);
foo.test();
return EXIT_SUCCESS;
}
错误是:
stream1.cpp:19: error: no match for 'operator<<' in '*((Foo<MyStream>*)this)->Foo<MyStream>::out_ << std::endl'
stream1.cpp:7: note: candidates are: std::ostream& MyStream::operator<<(const std::string&)
因此它可以输出字符串(请参见错误上方的行),但不仅仅是 std ::endl
,大概是因为 std::endl
不是字符串,但 operator<<
定义要求一个字符串。
模板化 operator<<
没有帮助:
template<class T>
std::ostream& operator<<(const T& s) { ... }
如何使代码工作?谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将其添加到您的 struct MyStream 中:
std::endl 是一个附加换行符并刷新底层流的函数;此函数签名接受该函数并将其应用于
ostream
成员。然后,作为测试,定义
foo::test
as将正确输出
You need to add this to your
struct MyStream
:std::endl
is a function that appends a newline and flushes the underlying stream; this function signature accepts that function and applies it to theostream
member.Then, as a test, defining
foo::test
aswill correctly output