是否可以避免在初始化列表中使用static_cast? [英] Is it possible to avoid static_cast in initializer list?

查看:173
本文介绍了是否可以避免在初始化列表中使用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.

这篇关于是否可以避免在初始化列表中使用static_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆