多个输出运算符?
是否可以为枚举定义多个输出运算符?我想使用这个
std::ostream& operator<< (std::ostream& os, my_enum e);
运算符来(1)打印人类可读的文本并(2)将其转换为一些代码以存储在数据库中。
谢谢
is it possible to define multiple output operators for an enum? I want to use this
std::ostream& operator<< (std::ostream& os, my_enum e);
operator to (1) print a human readable text and to (2) convert it to some code for storing in a database.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
创建将返回一些对象而不是 ostream& 的包装器它将处理打印。在您的情况下,它将对象打印人类可读的值和对象打印数据库代码。这是打印人类可读形式和整数形式的粗略示例。
ostream_enum_wrapper_ human
类及其运算符 <<用于打印人类可读的形式,类ostream_enum_wrapper_int
及其 <<用于打印整数代码。从 ostream& 切换对于包装器,运算符 <<使用 (ostream&,wrappertag),它将 ostream 对象包装在包装器内部并返回包装对象。那么接下来<<运算符在包装器对象上调用,而不是在 ostream& 上调用,并且包装器类知道如何打印值。打印 00two
Create wrappers which will return some object instead of ostream& which will handle printing. In your case it will object for printing humand-readable value and object for printing database code. Here's rough example which prints human-readable form and integer form.
ostream_enum_wrapper_human
class with its operator << is used for printing human-readable form, classostream_enum_wrapper_int
with its << is used for printing integer code. To switch from ostream& to wrapper, operator << (ostream&, wrappertag) is used, which wraps ostream object inside of wrapper and returns wrapped object. So next << operator is called on wrapper object, not on ostream&, and wrapper class knows how to print value.prints zero0two
您可以利用第一个参数的重载。
然后编写流修饰符,将流转换为包装databasefmt类,以便该修改流的下一个输出将是您枚举的数据库输出。打印代码如下所示:
包装器如下所示:
You may take advantage of overloading by the first argument.
Then write stream modifier that converts the stream to wrapping databasefmt class, so that next output to that modified stream would be database output for you enum. The printing code would look like this:
and the wrapper like this:
当然为什么不呢?您必须创建一个
ostream
派生类来实现写入数据库,与ofstream
写入文件非常相似。魔鬼在于细节。Sure why not? You would have to create an
ostream
derived class which implements writing to the database, much the same asofstream
writes to a file. The devil is in the details.首选方法是使用 std::ios_base::xalloc,然后使用 std::ios_base::iword:
之后您可以添加自己的一些奇特的操纵器,而不是直接使用 std::ios_base::iword。像这样:
The preferred way is to use std::ios_base::xalloc and then std::ios_base::iword:
After that you could add some fancy manipulator of your own, instead of using std::ios_base::iword directly. Like this:
这个解决方案远非完美;但对于你的问题,没有一个真正好的解决方案。
正如您所看到的,我将流运算符放在命名空间中。因此,我必须将命名空间包含到当前命名空间中。这只需通过简单的 using 声明即可完成。
诀窍是将 using 声明放在尽可能小的范围内。
This solution is far from perfect; but there is no really nice one to your problem.
As you can see I put the stream operators in namespaces. As a result I have to include the namespace into the current one. This is simply done with a simple using declaration.
The trick is to put the using declaration in the smalest scope possible.