gpt4 book ai didi

c++ - 来自std::string to unsigned char[], an error “non-constant-expression cannot be narrowed”

转载 作者:行者123 更新时间:2023-12-02 10:10:47 24 4
gpt4 key购买 nike

没有错误消息:non-constant-expression cannot be narrowed from type 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >::value_type' (aka 'char') to 'unsigned char' in initializer list [-Wc++11-narrowing]
MSVC GCC 将问题视为警告,但是 Clang 将其视为错误。
编码:

enum Encoding { ERR = -1, NONE, ASCII, UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE };

Encoding CheckBOM(const std::string& data) {
unsigned int DataSize = data.length();
if (DataSize < 4)
return ERR;
// the following line is the cause of the problem
unsigned char BOM[4] = { data[0], data[1], data[2], data[3] }; // <-- This line is what the error message points to

if (BOM[0] == 0xef && BOM[1] == 0xbb && BOM[2] == 0xbf)
return Encoding::UTF8;
else if (BOM[0] == 0xff && BOM[1] == 0xfe && BOM[2] == 0x00 && BOM[3] == 0x00)
return Encoding::UTF32LE;
else if (BOM[0] == 0x00 && BOM[1] == 0x00 && BOM[2] == 0xfe && BOM[3] == 0xff)
return Encoding::UTF32BE;
else if (BOM[0] == 0xff && BOM[1] == 0xfe)
return Encoding::UTF16LE;
else if (BOM[0] == 0xfe && BOM[1] == 0xff)
return Encoding::UTF16BE;
return Encoding::NONE;
}
我曾尝试解决该问题,但由于不了解,所以无法解决。
我该如何解决?

最佳答案

由于std::stringbasic_string<char>,因此您要为char分配带符号的unsigned char类型,从而缩小范围。
狭义的转换可以说是隐式转换,其中转换后的类型不能在所有情况下都由目标类型表示,这种情况就是将有符号转换为无符号。
由于该标准不允许在聚合初始化(即braced-init-list)中缩小转换范围,因此您必须自己“手动”完成操作。
dcl.init.aggr#4.2

[...] If that initializer is of the form assignment-expression or = assignment-expression and a narrowing conversion ([dcl.init.list]) is required to convert the expression, the program is ill-formed.[...]


dcl.init.list#7

A narrowing conversion is an implicit conversion

[...]


[可能的隐式转换列表,分析中不需要此列表]

[...]

[Note: As indicated above, such conversions are not allowed at the top level in list-initializations.— end note]

[Example:

[...]

unsigned char uc1 = {5}; // OK: no narrowing needed

unsigned char uc2 = {-1}; // error: narrows

unsigned int ui1 = {-1}; // error: narrows

[...]


为了避免错误/警告,您可以将其强制转换为 unsigned char:
unsigned char BOM[4] = { static_cast<unsigned char>(data[0]), static_cast<unsigned char>(data[1]), static_cast<unsigned char>(data[2]), static_cast<unsigned char>(data[3])};
Live demo
或者,作为 suggested by @RemyLebeau,您可以使用:
const unsigned char * pdata = reinterpret_cast<const unsigned char *>(data.c_str()); 
unsigned char BOM[4] = { pdata[0], pdata[1], pdata[2], pdata[3] };
或更简单:
unsigned char BOM[4]; 
std::memcpy(BOM, data.c_str(), 4);
这需要 #include<cstring>

关于c++ - 来自std::string<char> to unsigned char[], an error “non-constant-expression cannot be narrowed” ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63621156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com