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:
type | description |
byte_string | A byte string to return on errors |
wide_string | A wide string to return on errors |
Codecvt* | A pointer to a conversion object |
state_type | A conversion state object, accessed with member state |
size_t | A conversion count, accessed with member converted |
Member functions
- (constructor)
- Construct wstring_convert (public member function
)
- (destructor)
- Destroy wstring_convert (public member function
)
Conversion:
- from_bytes
- Convert from bytes (public member function
)
- to_bytes
- Convert to bytes (public member function
)
Observers:
- converted
- Conversion count (public member function
)
- state
- Conversion shift state (public member function
)
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]
|