是否可以避免在初始化列表中使用static_cast?

是否可以避免在初始化列表中使用static_cast?

问题描述:

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

In my code base I often initialize array or vector if bytes using the following the syntax:

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

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

I get the following error from 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,
                        ^~~~~~~~~~~~~

编译器建议我添加一个static_cast来使错误静音.我知道强制转换会起作用,但是我想知道是否有可能避免强制转换并保持语法已经很优雅?

The compiler suggest me to add a static_cast to silence the error. I know the cast will work, but I wonder if it is possible to avoid the cast and to keep the syntax as elegant as it is already ?

谢谢您的帮助.

没有解决之道.

实际上,您必须使用演员表. foo >> 8& c.是类型为int的表达式,并且不能依赖初始化程序列表中的转换范围.只有不合格的编译器才会使用您提供的代码发布诊断信息.

In fact you must use a cast. foo >> 8 &c. are expressions of type int, and you must not rely on narrowing conversions in initialiser lists. Only a non-conforming compiler would refrain from issuing a diagnostic with the code you provide.