独自のオブジェクトを STL ストリームに出力したいのですが、フォーマットはカスタマイズされています。私はこのようなものを思いつきましたが、ロケールとインビューを使用したことがないので、これが理にかなっているかどうか、MyFacet と operator<< を実装する方法がわかりません。
私の質問は次のとおりです:これは理にかなっていますか? MyFacet と operator<< を実装する方法は?
以下は、私がやりたいことを示す簡単な例です。
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"