且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

字符串文字转换为basic_string< unsigned char>

更新时间:2023-11-14 19:26:28

狭窄的字符串文字被定义为const char,并且没有无符号的字符串文字[1],因此您必须进行强制转换:

Narrow string literals are defined to be const char and there aren't unsigned string literals[1], so you'll have to cast:

ustring s = reinterpret_cast<const unsigned char*>("Hello, UTF-8");

当然,您可以将较长的内容放入内联函数中:

Of course you can put that long thing into an inline function:

inline const unsigned char *uc_str(const char *s){
  return reinterpret_cast<const unsigned char*>(s);
}

ustring s = uc_str("Hello, UTF-8");

或者您可以只使用basic_string<char>并在处理UTF-8时有99.9%的时间摆脱它.

Or you can just use basic_string<char> and get away with it 99.9% of the time you're dealing with UTF-8.

[1]除非char是无符号的,但是无论它是否是实现定义的,等等,等等.

[1] Unless char is unsigned, but whether it is or not is implementation-defined, blah, blah.