Joh*_*ing 2 c++ string unicode internationalization
谈到国际化和Unicode,我是一个白痴美国程序员.这是交易.
#include <string>
using namespace std;
typedef basic_string<unsigned char> ustring;
int main()
{
static const ustring my_str = "Hello, UTF-8!"; // <== error here
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这会产生意外的抱怨:
cannot convert from 'const char [14]' to 'std::basic_string<_Elem>'
也许我今天喝了错咖啡.我该如何解决?我可以保留基本结构:
ustring something = {insert magic incantation here};
?
窄字符串文字被定义为const char全没有无符号的字符串文字[1],所以你必须投:
ustring s = reinterpret_cast<const unsigned char*>("Hello, UTF-8");
Run Code Online (Sandbox Code Playgroud)
当然你可以把那么长的东西放到内联函数中:
inline const unsigned char *uc_str(const char *s){
return reinterpret_cast<const unsigned char*>(s);
}
ustring s = uc_str("Hello, UTF-8");
Run Code Online (Sandbox Code Playgroud)
或者你可以在basic_string<char>99.9%的时间内使用它来逃避UTF-8.
[1]除非char是无符号的,否则它是否是实现定义的,等等,等等.