我希望能够为对象定义流运算符( <<
、 >>
),但要有多个流运算符,以便我可以根据上下文使用不同的集合。例如,如果我有一个对象如下:
struct Foo {
int a;
};
然后在某些地方我希望能够使用这个
std::ostream& operator<<(std::ostream& out, const Foo& foo) {
out<<foo.a;
}
在其他情况下我更愿意使用这个
std::ostream& operator<<(std::ostream& out, const Foo& foo) {
out<<"'"<<foo.a<<"'";
}
但我看不出如何同时定义这两者。
我正在提交我自己的答案,但我希望其他人在过去有理由比我更深入地思考这个问题,并且最好在大型应用程序中有一个有组织的方式来做这件事(因此术语“问题标题中的“管理”)。
最佳答案
创建一个操纵器:一个简单的代理,它只为替代格式提供一个名称(和一个重载槽)。
// default format
std::ostream& operator<<(std::ostream& out, const Foo& foo) {
return out<<foo.a;
}
// custom format
// helper class
struct print_quoted_manip {
Foo const &ref;
print_quoted_manip( Foo const &in )
: ref( in ) {}
};
// implementation
std::ostream& operator<<( std::ostream& out, print_quoted_manip o )
{ return out << '\'' << o.ref << '\''; }
// the manipulator
print_quoted_manip print_quoted( Foo const &in )
{ return print_quoted_manip( in ); }
// usage
std::cout << print_quoted( my_foo );
您可以轻松地将其模板化以在任何类型的对象周围加上引号。
关于c++ - 为同一对象管理多个流运算符(operator<<, >>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16335060/