从std :: string <char>到unsigned char [],错误“无法缩小非常数表达式”

问题描述

有错误消息:

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;
}

我试图解决该问题,但由于不了解,所以无法解决。

我该如何解决?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)