是否可以为枚举定义多个输出运算符?我想用这个
std::ostream& operator<< (std::ostream& os, my_enum e);
操作者(1)打印人类可读文本并(2)将其转换为某些代码以存储在数据库中.
谢谢
解决方法:
创建将返回一些对象的包装器而不是ostream&这将处理打印.在您的情况下,它将反对打印humand可读的值和对象以打印数据库代码.这是打印人类可读形式和整数形式的粗略示例. ostream_enum_wrapper_human类及其运算符<<用于打印人类可读的表单,类ostream_enum_wrapper_int及其<<用于打印整数代码.从ostream&切换to wrapper,operator<< (ostream&,wrappertag)用于将ostream对象包装在包装器内并返回包装对象.所以下一个<<在包装器对象上调用operator,而不是在ostream&上,而包装类知道如何打印值.
#include <iostream>
using namespace std;
class ostream_enum_wrapper_human
{
public:
ostream& out;
ostream_enum_wrapper_human(std::ostream& _out) : out(_out){}
};
class ostream_enum_wrapper_int
{
public:
std::ostream& out;
ostream_enum_wrapper_int(std::ostream& _out) : out(_out){}
};
enum T{zero,one,two};
struct human_readable{} HumanReadable;
ostream_enum_wrapper_human operator << (ostream& out, human_readable){
return ostream_enum_wrapper_human(out);
}
struct print_int{} PrintInt;
ostream_enum_wrapper_int operator << (ostream& out, print_int){
return ostream_enum_wrapper_int(out);
}
ostream& operator << (ostream_enum_wrapper_human out, T t)
{
switch(t) {
case zero: out.out << "zero"; break;
case one: out.out << "one"; break;
case two: out.out << "two"; break;
}
return out.out;
}
ostream& operator << (ostream_enum_wrapper_int out, T t)
{
return out.out << static_cast<int>(t);
}
int main()
{
cout << HumanReadable << zero << PrintInt << zero << HumanReadable << two;
}