Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created January 11, 2014 02:40
Show Gist options
  • Save dgodfrey206/8366305 to your computer and use it in GitHub Desktop.
Save dgodfrey206/8366305 to your computer and use it in GitHub Desktop.
Synchronization of locales between streams.
#include <iostream>
#include <sstream>
static int tied_stream()
{
static int i = std::ios_base::xalloc(); return i;
}
static int first_check()
{
static int i = std::ios_base::xalloc(); return i;
}
void sync_locales(std::ios_base::event evt, std::ios_base& str, int index)
{
if (evt & std::ios_base::imbue_event)
{
void*& p = str.pword(index);
if (p)
{
std::ios_base& other = *static_cast<std::ios_base*>(p);
other.imbue(str.getloc());
}
}
}
void tie_locales(std::ios_base& src, std::ios_base& dest)
{
static long& done = src.iword(first_check());
static void*& stream = dest.pword(tied_stream());
if (!done)
{
dest.imbue(src.getloc());
done = true;
}
if (!stream)
{
stream = &src;
dest.register_callback(sync_locales, tied_stream());
}
}
int main()
{
std::ostringstream o1, o2;
o1.imbue(std::locale("en_US.UTF8"));
std::cout << std::boolalpha;
std::cout << "First check: " << (o1.getloc() == o2.getloc()) << std::endl;
tie_locales(o1, o2);
std::cout << "Second check: " << (o1.getloc() == o2.getloc()) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment