Declaration
template <class Type, class CharT> std::basic_string<Type> code_convert(const std::basic_string<CharT>& src, cost std::codecvt<wchar_t, char, mbstate_t>& cvt); template <class Type, class CharT> std::basic_string<Type> code_convert(const std::basic_string<CharT>& src, const std::locale& loc = std::locale()); template <class Type, class Source> std::basic_string<Type> code_convert(const Source* src, const std::codecvt<wchar_t, char, mbstate_t>& cvt); template <class Type, class Source> std::basic_string<Type> code_convert(const Source* src, const std::locale& loc = std::locale());
Overview
code_convert は,ナロー文字 (char) <-> ワイド文字 (wchar_t) の相互変換を行うためのクラスです.std::basic_string<CharT> から std::basic_string<Type>,または Source* から std::basic_string<Type> への変換を試みます.実際の変換処理は,std::codecvt<wchar_t, char, mbstate_t> に依存します.
Example
#ifndef CLX_USE_WCHAR #define CLX_USE_WCHAR #endif // CLX_USE_WCHAR #include <iostream> #include <string> #include "clx/code_convert.h" int main(int argc, char* argv[]) { try { std::cout.imbue(std::locale("japanese")); std::wcout.imbue(std::locale("japanese")); // char -> wchar_t std::string s = "はろーわーるど"; std::wstring wcvt = clx::code_convert<wchar_t>(s, std::locale("japanese")); std::wcout << L"char -> wchar_t" << std::endl; std::wcout << L"-----" << std::endl; std::cout << "original: " << s << " (" << s.size() << ")" << std::endl; std::wcout << L"convert: " << wcvt << L" (" << wcvt.size() << L")" << std::endl; std::wcout << std::endl; // wchar_t -> char std::wstring ws = L"ハローワールド"; std::string cvt = clx::code_convert<char>(ws, std::locale("japanese")); std::cout << "wchar_t -> char" << std::endl; std::cout << "-----" << std::endl; std::wcout << L"original: " << ws << L" (" << ws.size() << L")" << std::endl; std::cout << "convert: " << cvt << " (" << cvt.size() << ")" << std::endl; } catch (std::runtime_error& e) { std::cerr << e.what() << std::endl; std::exit(-1); } return 0; }
Result char -> wchar_t ----- original: はろーわーるど (14) convert: はろーわーるど (7) wchar_t -> char ----- original: ハローワールド (7) convert: ハローワールド (14)