Search code examples
c++stliostreamfacet

How to format my own objects when using STL streams?


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<<.

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"

Solution

  • 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.

    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!