c++ - 使用 std::uint8_t 作为键初始化 map 时的警告

标签 c++ compiler-warnings literals

问题

我正在尝试创建 std::uint8_t -> char 的映射,并使用一些值初始化它:

const std::map<std::uint8_t, char> ScenarioReader::alphabet = {
    { 0x12, 'b' },
    { 0x13, 'c' },
    { 0x15, 'a' },
    { 0x16, 'f' },
    ...
}

这会生成编译器警告,因为这些整数文字(0x12等)被识别为无符号整数,它们大于std::uint8_t :

1>d:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\utility(172): warning C4244: 'initializing': conversion from '_Ty' to '_Ty1', possible loss of data
1>        with
1>        [
1>            _Ty=unsigned int
1>        ]
1>        and
1>        [
1>            _Ty1=uint8_t
1>        ]
1>d:\my-project\src\myfile.cpp(75): note: see reference to function template instantiation 'std::pair<const _Kty,_Ty>::pair<unsigned int,char,0>(_Other1 &&,_Other2 &&) noexcept' being compiled
1>        with
1>        [
1>            _Kty=uint8_t,
1>            _Ty=char,
1>            _Other1=unsigned int,
1>            _Other2=char
1>        ]
1>d:\my-project\src\myfile.cpp(12): note: see reference to function template instantiation 'std::pair<const _Kty,_Ty>::pair<unsigned int,char,0>(_Other1 &&,_Other2 &&) noexcept' being compiled
1>        with
1>        [
1>            _Kty=uint8_t,
1>            _Ty=char,
1>            _Other1=unsigned int,
1>            _Other2=char
1>        ]

解决方案

我知道有两种可能的方法来解决此问题:

1) 禁用此部分的警告

#pragma warning( push )
#pragma warning( disable : 4244 )
const std::map<std::uint8_t, char> ScenarioReader::alphabet = {
    { 0x12, 'b' },
    { 0x13, 'c' },
    { 0x15, 'a' },
    { 0x16, 'f' },
    ...
}
#pragma warning( pop)

2)显式转换每个键

const std::map<std::uint8_t, char> ScenarioReader::alphabet = {
    { static_cast<std::uint8_t>(0x12), 'b' },
    { static_cast<std::uint8_t>(0x13), 'c' },
    { static_cast<std::uint8_t>(0x15), 'a' },
    { static_cast<std::uint8_t>(0x16), 'f' },
    ...
}

我对这两种方法都不是特别满意,但第二种对我来说尤其难看。

我是否缺少一个更简单的解决方案?

最佳答案

integer literal永远不可能是 std::uint8_t。您可以创建 explicit cast 而不是使用 static_cast字面意思:

const std::map<std::uint8_t, char> alphabet = {
    { std::uint8_t(0x12), 'b' },
    { std::uint8_t(0x13), 'c' },
    { std::uint8_t(0x15), 'a' },
    { std::uint8_t(0x16), 'f' },
};

关于c++ - 使用 std::uint8_t 作为键初始化 map 时的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64098003/

相关文章:

c++ - 运算符重载 - 索引不打印

c++ - 在 MSVC 2017 中检测警告

c++ - MSVC C/C++ 编译器未定义行为警告

javascript - 获取对象文字键的值

qt - 如何定义 qreal 文字

c++ - 是否可以将文字值传递给 C++ 中的 lambda 一元谓词?

c++ - 旋转矩阵的 Y 旋转

c++ - 不能使用线程构造函数

c++ - 通过 GLSL 着色器传递数据

c - GCC 优化器的未初始化警告