• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    class template
    <locale>

    std::wstring_convert

    namespace std {
      template <class Codecvt, class Elem = wchar_t,
                class Wide_alloc = std::allocator<Elem>,
                class Byte_alloc = std::allocator<char> >
      class wstring_convert;
    }
    

    概要

    wstring_convertは、ワイド文字列とバイト文字列を相互変換するクラスである。

    バイト文字列とは、ひとつの文字を表すのに可変長のバイト数を必要とする、UTF-8やShift_JISのような文字コードの文字列である。

    ワイド文字列とは、ひとつの文字を表すのに固定長のバイト数を必要とする、UTF-16やUTF-32のような文字コードの文字列である。

    このクラスのfrom_bytes()メンバ関数を使用することによってバイト文字列からワイド文字列への変換ができ、to_bytes()メンバ関数を使用することによってワイド文字列からバイト文字列への変換ができる。

    テンプレートパラメータは、以下を意味する:

    • Codecvt : コード変換を行うクラス。<codecvt>ヘッダでいくつかの変換器が定義されている。
    • Elem : ワイド文字列の内部表現で使用する文字型。
    • Wide_alloc : ワイド文字列のアロケータ。
    • Byte_alloc : バイト文字列のアロケータ。

    テンプレートパラメータの設定例:

    目的 バイト文字列型 ワイド文字列 パラメータ
    UTF-8とUTF-16の変換 std::string std::u16string std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>
    UTF-8とUTF-32の変換 std::string std::u32string std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t>

    非推奨・削除の詳細

    Unicodeの文字コード変換を行うこれらのクラスは、不正なコードポイントに対する安全なエラー処理の方法を提供していなかったため、セキュリティ上の欠陥があった。

    仕様もあいまいであったため、不正なコードポイントに対してどのように振る舞うかも不明であった。

    Unicode以外のShift_JISやBig5といった文字コードの利用が急激に減少している。標準ライブラリでの現代的なUnicodeの変換機能は非常に必要とされているが、<codecvt>とそれに関連する機能の設計はお粗末なものだった。将来より良いものを作るために、これらの機能は非推奨・削除とする。

    標準ライブラリにUnicodeの文字コード変換をする代替機能はないため、他の専門特化した文字コード変換のライブラリを使用すること。

    メンバ関数

    名前 説明 対応バージョン
    (constructor) コンストラクタ C++11
    (destructor) デストラクタ C++11
    operator= 代入演算子 C++11
    from_bytes バイト文字列からワイド文字列に変換する C++11
    to_bytes ワイド文字列からバイト文字列に変換する C++11
    converted 変換した要素数を取得する C++11
    state 変換の状態を取得する C++11

    メンバ型

    名前 説明 対応バージョン
    byte_string バイト列型 std::basic_string<char, char_traits<char>, Byte_alloc> C++11
    wide_string ワイド文字列型 std::basic_string<Elem, char_traits<Elem>, Wide_alloc> C++11
    state_type ストリームのマルチバイト文字の変換の状態を表す型 Codecvt::state_type C++11
    int_type 文字に対応する値を表す数値型 wide_string::traits_type::int_type C++11

    #include <iostream>
    #include <string>
    #include <locale>
    #include <codecvt>
    
    int main()
    {
      // UTF-8とUTF-32の相互変換を行うコンバーター
      std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
    
      // UTF-8からUTF-32に変換
      std::string u8str = u8"あいうえお";
      std::u32string u32str = converter.from_bytes(u8str);
    
      // コードポイント数を取得
      std::size_t codepoint_count = u32str.size();
      std::cout << codepoint_count << std::endl;
    }
    

    出力

    5
    

    バージョン

    言語

    • C++11

    処理系

    • Clang: 3.0 , 3.1 , 3.2 , 3.3 , 3.4
    • GCC: 5.1
    • ICC:
    • Visual C++: 2010 , 2012 , 2013

    参照