【发布时间】:2011-02-06 09:56:39
【问题描述】:
以下代码在应该只输出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) { ... }
我怎样才能使代码工作?谢谢!
【问题讨论】:
标签: c++ templates stl operator-overloading