class template
<locale>

std::wstring_convert

template < class Codecvt,           class Elem = wchar_t,           class Wide_alloc = std::allocator<Elem>,           class Byte_alloc = std::allocator<char> > class wstring_convert;
Convert to/from wide string
Performs conversions between wide strings and byte strings (on either direction) using a conversion object of type Codecvt.

The object acquires ownership of the conversion object, becoming responsible for its deletion at some point (when it is itself destroyed).

Template parameters

Codecvt
Type of the conversion object: This shall be a class with the same properties as the codecvt locale facet, such as one of the standard classes defined in header <codecvt>.
Elem
Wide character type.
This shall correspond to the internal type of the codecvt-like conversion object.
Wide_alloc
Allocator for elements of type Elem, used as template argument for the wide string type.
Defaults to: allocator<Elem>
Byte_alloc
Allocator for elements of type char, used as template argument for the byte string type.
Defaults to: allocator<char>

Object state

The object stores internally the following data elements:
typedescription
byte_stringA byte string to return on errors
wide_stringA wide string to return on errors
Codecvt*A pointer to a conversion object
state_typeA conversion state object, accessed with member state
size_tA conversion count, accessed with member converted

Member types

member typedefinitionnotes
byte_stringbasic_string<char,char_traits<char>,Byte_alloc>narrow string type
wide_stringbasic_string<Elem,char_traits<Elem>,Wide_alloc>wide string type
state_typeCodecvt::state_type
int_typechar_traits<Elem>::int_type

Member functions


Conversion:


Observers:


Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// converting from UTF-32 to UTF-8
#include <iostream>       // std::cout, std::hex
#include <string>         // std::string, std::u32string
#include <locale>         // std::wstring_convert
#include <codecvt>        // std::codecvt_utf8
#include <cstdint>        // std::uint_least32_t

int main ()
{
  std::u32string str32 ( U"\U00004f60\U0000597d" );  // ni hao (你好)
  std::string str8;

  std::wstring_convert<std::codecvt_utf8<char32_t>,char32_t> cv;

  str8 = cv.to_bytes(str32);

  // print contents (as their hex representations):
  std::cout << std::hex;

  std::cout << "UTF-32: ";
  for (char32_t c : str32)
    std::cout << '[' << std::uint_least32_t(c) << ']';
  std::cout << '\n';

  std::cout << "UTF-8 : ";
  for (char c : str8)
    std::cout << '[' << int(static_cast<unsigned char>(c)) << ']';
  std::cout << '\n';

  return 0;
}

Output:

UTF-32: [4f60][597d]
UTF-8 : [e4][bd][a0][e5][a5][bd]