是否可以避免初始化列表中的static_cast?

AMD*_*MDG 6 c++ initializer-list narrowing

在我的代码库中,我经常使用以下语法初始化数组或向量(如果是字节):

uint16_t foo = 0xAB, bar = 0xCD

// bytes = { 0xA, 0xB, 0xC, 0xD }
std::array<uint8_t, 4> bytes = {{
    foo >> 8,
    foo & 0x00FF,
    bar >> 8,
    bar & 0x00FF
}};
Run Code Online (Sandbox Code Playgroud)

我从clang ++中得到以下错误:

error: non-constant-expression cannot
 be narrowed from type 'int' to 'value_type' (aka 'unsigned char') in initializer list [-Wc++11-narrowing]
                        foo >> 8,
                        ^~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

编译器建议我添加一个static_cast来消除错误.我知道演员会工作,但我想知道是否有可能避免演员表并保持语法优雅,因为它已经存在?

谢谢您的帮助.

Bat*_*eba 3

没有优雅的方法来解决这个问题。

事实上你必须使用强制转换。foo >> 8&C。是类型 的表达式int,并且您不能依赖初始化列表中的缩小转换。只有不合格的编译器才会避免对您提供的代码发出诊断。