Search code examples
copylocalestringstream

How to copy an imbued facet from a stringstream?


Assuming I have imbued a facet in a stringstream:

std::stringstream msgStream;
{
   bpt::time_facet * afacet = new bpt::time_facet("%Y-%m-%d\t%H:%M:%S\t0.%f");
   msgStream.imbue(std::locale(msgStream.getloc(),afacet));
}
// How to access the facet in order to copy it?

How can I copy this facet from msgStream in order to imbue a new copy in another stringstream? Is there a way to retrieve the facet pointer later if afacet goes out of scope but msgStream does not.


Solution

  • You're imbuing a std::locale, not a bpt::time_facet.

    You can access the current locale of the std::stringstream from msgStream.getloc()

    With the std::locale object, you can access the facet with it's member facet:

    std::locale myLocale = msgStream.getloc();
    myLocale.facet; //Operate on the facet. Returns std::locale::facet.
    

    You can then cast it to your bpt::time_facet if required.

    For more info see class references - imbue, facet, stringstream, locale