我想将我自己的对象输出到 STL 流,但使用自定义格式。我想到了这样的东西,但由于我之前从未使用过 locale 和 imbue,所以我不知道这是否有意义以及如何实现 MyFacet 和 operator<<。
所以我的问题是:这是否有意义以及如何实现 MyFacet 和运算符<<?
以下是一个简化的示例,向您展示了我想做的事情。
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"
最佳答案
实现您自己的运算符<< 以进行跟踪通常是个好主意。但是我从来不需要灌输语言环境。但是我试过了,效果很好。这是我所做的:
class my_facet : public std::locale::facet
{
public:
enum option{
use_string,
use_numeric
};
//Unique id for facet family, no locale can contain two
//facets with same id.
static std::locale::id id;
my_facet(option o=use_numeric):
facet(0),
_option(o)
{//Initialize reference count to zero so that the memory
//management will be handled by locale
};
option get_option() const {return _option;};
protected:
option _option;
};
std::locale::id my_facet::id(123456); //Facet family unique id
std::ostream& operator<<(std::ostream& os, const myobj& o)
{
std::locale const& l = os.getloc();
if( std::has_facet<my_facet>(l) ){
my_facet const& f = std::use_facet<my_facet>(l);
switch(f.get_option()){
case my_facet::use_numeric:
os << "Using numeric! ";
break;
case my_facet::use_string:
os << "Using string! ";
break;
default:
os << "Unhandled case.. ";
break;
}
return os;
}
os << "Default case when no facet has been set";
return os;
}
然后用这个方面来灌输语言环境:
std::locale mylocale(locale("US"), new my_facet(my_facet::use_numeric));
std::cout.imbue(mylocale);
然而,更优雅的方法是实现可在语言环境中替换的同一方面系列的不同方面。
关于c++ - 使用 STL 流时如何格式化我自己的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1096291/