当使用STL流时如何格式化我自己的对象? [英] How to format my own objects when using STL streams?

查看:153
本文介绍了当使用STL流时如何格式化我自己的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将自己的对象输出到STL流,但使用自定义格式。我想出了这样的事情,但因为我从来没有使用locale和imbue之前,我不知道这是否有意义,以及如何实现MyFacet和操作符< <。

I want to output my own object to a STL stream but with customized formatting. I came up with something like this but since I never used locale and imbue before I have no idea if this makes sense and how to implement MyFacet and operator<<.

所以我的问题是:这是有意义的,如何实现MyFacet和运算符<< ?

So my questions are: does this make sense and how to implement MyFacet and operator<< ?

以下是一个简单的例子,说明我想做什么。

The following is a simplified example which shows you what I want to do.

struct MyObject
{
  int i;
  std::string s;
};

std::ostream &operator<<(std::ostream &os, const MyObject &obj)
{
    if (????)
    {
        os << obj.i;
    }
    else
    {
        os << obj.s;
    }
}

MyObject o;
o.i = 1;
o.s = "hello";

std::cout.imbue(locale("", new MyFacet(MyFacet::UseInt)));
std::cout << o << std::endl;    // prints "1"

std::cout.imbue(locale("", new MyFacet(MyFacet::UseString)));
std::cout << o << std::endl;    // prints "hello"


推荐答案

一般用于允许基于存在的本地(实际上指定的区域设置)格式化的相同对象的不同输出/输入格式化。有关此文章的好文章,请参阅: http://www.cantrip.org/locale.html 。现在也许是因为你的例子很简单,但对我来说,你想要一个聪明的方式来打印一个对象的一部分或另一个之间切换。如果是这种情况,它可能更简单只是重载每个类型的流运算符,并使用外部的if开关。

Well, a locale is generally used to allow different output/input formatting of the same object based on the local (the specified locale in fact) formatting which is present. For a good article on this see: http://www.cantrip.org/locale.html. Now maybe its because your example above is quite simplified, but to me it looks like you are trying to come up with a clever way to switch between printing one part of an object or another. If that is the case it might be simpler do just overload the stream operator for each type and use the if switch externally.

无论如何,我不会假装我是facets和地区的专家,但看看那篇文章,它很彻底,会给你一个比我更好的解释!

Anyway, I'm not going to pretend that I'm an expert in facets and locales but have a look at that article, its pretty thorough and will give you a better explanation than I will!

这篇关于当使用STL流时如何格式化我自己的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆