Fra*_*ank 4 c++ templates stl operator-overloading
以下代码在输出时只出现错误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;
}
Run Code Online (Sandbox Code Playgroud)
错误是:
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&)
Run Code Online (Sandbox Code Playgroud)
所以它可以输出一个字符串(参见错误上方的行),但不仅仅是std::endl,可能因为std::endl它不是一个字符串,而是operator<<定义要求一个字符串.
模板化operator<<没有帮助:
template<class T>
std::ostream& operator<<(const T& s) { ... }
Run Code Online (Sandbox Code Playgroud)
如何使代码工作?谢谢!
您需要将此添加到您的struct MyStream:
std::ostream& operator<<( std::ostream& (*f)(std::ostream&) )
{
return f(*out_);
}
Run Code Online (Sandbox Code Playgroud)
std::endl是一个附加换行符并刷新底层流的函数; 此函数签名接受该函数并将其应用于ostream成员.
然后,作为测试,定义foo::test为
void test() {
(*out_) << "start";
(*out_) << std::endl;
(*out_) << "done";
}
Run Code Online (Sandbox Code Playgroud)
将正确输出
start done
| 归档时间: |
|
| 查看次数: |
1673 次 |
| 最近记录: |