Wide/narrow character conversion using output iterators

This approach converts between narrow and wide characters using output iterators.

#include <x/codecvtiter.H>
#include <x/locale.H>

#include <string>
#include <algorithm>

x::locale conv_locale;

std::string str;

std::wstring wstr;

typedef std::back_insert_iterator<std::wstring> ins_iter_t;

typedef x::ocodecvtiter<ins_iter_t>::ctow_iter_t ctow_ins_iter_t;

typedef ctow_ins_iter_t::iter iter;

ins_iter_t wstr_ins_iter(wstr);

iter ins(ctow_ins_iter_t::create(wstr_ins_iter, conv_locale));

ins=std::copy(str.begin(), str.end(), ins);


The template parameter of x::ocodecvtiter<ins_iter_t>::ctow_iter_t, ins_iter_t is any wide character output iterator class.

The x::ocodecvtiter<ins_iter_t>::ctow_iter_t template defines a create() method that returns an iter type, also defined in the template. iter is an output iterator defines an output iterator that receives wide characters, converts them to narrow characters in the specified locale, which then get written to the narrow character output iterator. The first parameter to create() is a wide iterator class output iterator instance. The optional second parameter defaults to the global locale, and defines the narrow to wide character conversion.

The iter iterator uses internal buffering. Invoke the flush() method, after the entire narrow character sequence gets written to the output iterator, to flush the internal buffers and write any remaining wide character sequence to the underlying output iterator, whose new value gets returned by flush(). Following the call to flush(), the iter iterator is no longer useful.

x::ocodecvtiter<ins_iter_t>::wtoc_iter_t defines an analogous output iterator that converts wide characters to narrow characters.

typedef x::ocodecvtiter_bytype<ins_iter_t, char, wchar_t>::iter_t ctow_ins_iter_t;

x::ocodecvtiter_bytype is an alternative way to select either ctow_iter_t or wtoc_iter_t, depending on the template's second and third parameters.