Boost logo

Boost :

From: Jonathan Turkanis (technews_at_[hidden])
Date: 2004-12-17 17:01:31


Robert Ramey wrote:
> Note the the serialization library contains code for doing exactly
> this.
> Its in the subdirectory Dataflow Iterators. It was needed to
> serialize strings to wide character archives and to serialize
> wstirngs to char archives.
>
> Robert Ramey
>
> Stefan Slapeta wrote:
>> Hi all,
>>
>> there have been many discussions (and proposals) on this topic in the
>> last years, but was there any result and is there _anything_ in boost
>> today that can be used to convert between std::string and
>> std::wstring?

The Iostreams library will contain this functionality, too. (I'm rewriting it as
we speak.)

When I finish, converting between wide and narrow strings should look like this:

    #include <boost/iostreams/code_converter.hpp>
    #include <boost/iostreams/copy.hpp>

    using namespace std;
    using namespace boost::io;

    // Function object type for widening strings.
    template<typename Codecvt>
    struct widener : unary_function<string, wstring> {
        wstring operator() (string s) const
        {
            wstring result;
            converter<Codecvt, istringstream> cvt(s);
            boost::io::copy(cvt, back_inserter(result));
            return result;
        }
    };

    // Function object type for narrowing strings.
    template<typename Codecvt>
    struct narrower : unary_function<wstring, string> {
        string operator() (wstring s) const
        {
            ostringstream result;
            converter<Codecvt, ostringstream> cvt(result);
            boost::io::copy(boost::make_iterator_range(s), cvt);
            return result.str();
        }
    };

The Dinkumware CoreX library also contains a component, wstring_convert, for
this purpose. Since it doesn't make a detour through streams, it might be more
efficient.

Jonathan


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk