Modifying a facet object
Posted on 2008-10-15
It seems that the way the C++ standard library is set up discourages modifying an existing facet object that is associated with a locale, because the only way to access a facet object is through std::use_facet, and std::use_facet returns a const reference.
But suppose, for example. you have a custom facet object that regulates the output of something like dates. And suppose the facet object has two internal flags to represent a date format: the American style of month, day, year, and the European style of day, month, year. It would be very convenient to create a stream manipulator function which allows you to toggle between the two styles, so you could do something like:
cout << euro_style << d << endl;
So the manipulator would be implemented as:
std::ostream& euro_style(std::ostream& os)
Of course, the above code doesn't work because std::use_facet returns a constant reference, and date_facet::set_euro_style() is a non-const member function. So in order to make it work, you need to use a const_cast, or use mutable internal variables in the facet object. This is no problem, but it says to me that the designers of the C++ I/O stream library are trying to discourage modification of facet objects. This makes me wonder if there is some reason why it is dangerous or unwise to modify a facet object that is already bound to a locale. Otherwise, why does use_facet return a constant reference?