What is the difference between std :: wstring_convert and std :: wbuffer_convert?

The locale header file contains two convenience interfaces: std::wstring_convertand std::wbuffer_convert. However, there are no examples of use.

Are there any brief examples to illustrate their customs and differences?

+5
source share
1 answer

std::wstring_convert

Given std::u32string(aka std::basic_string<char32_t>), which contains UTF-32 code units in the form of elements char32_t, here's how to convert it to a sequence of UTF-8 code blocks in bytes:

// Both <locale> and <codecvt> required

std::u32string input = U"Hello, World";

using Codecvt = std::codecvt_utf8<char32_t>;
std::wstring_convert<Codecvt, char32_t> converter;

// throws std::range_error if the conversion fails
std::string result = converter.to_bytes(input);

, quirk std::wstring_convert - , , ( std::basic_string, std::string), , std::basic_string<char, std::char_traits<char>, Allocator>.

, , - , <codecvt>. , , . std::codecvt<wchar_t> - .

std::wbuffer_convert

, out, std::ostream (a.k.a std::basic_ostream<char>), UTF-8. , , out << u8"Hello" . , UTF-32 ( std::u32string), - , out. std::wstring_convert , .

:

std::wbuffer<std::codecvt_utf8<char32_t>, char32_t> wout { out.rdbuf() };
std::u32string input = U"Hello";
wout << input;

out, , std::basic_stream<char32_t> UTF-32, ( ).

, std::wbuffer_convert std::wstring_convert, .

, , <codecvt>, : (.

+7

All Articles