创建字符数组,避免缩小 [英] Create array of chars avoiding narrowing

查看:108
本文介绍了创建字符数组,避免缩小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个单元测试,以根据预期的数组检查一些二进制数据.有问题的预期数组只是一系列字节,没有特别关系:

I am writing a unit test checking some binary data against an expected array. The expected array in question is just some series of bytes, doesn't matter specifically:

char expected[] = {0x42, 0xde, 0xad, 0xbe, 0xef};

这在C ++中可以很好地编译,但是对于C ++ 11,这会在缩小转换范围时发出警告.我使用-Werror进行编译,因为警告很重要,因此该行不会为我编译.据我所知,char没有字面后缀,所以看来我必须这样做:

This compiled fine in C++, but with C++11 this issues a warning on narrowing conversion. I compile with -Werror because warnings matter, so that line does not compile for me. As far as I'm aware, there's no literal suffix for char, so it seems I'd have to do:

char expected[] = {static_cast<char>(0x42), static_cast<char>(0xde), ... };

对我来说,这似乎很笨拙.有没有更好的方法来构造此字符数组? (除了删除-Werror或添加-Wno-narrowing之外.)

That seems pretty unwieldy to me. Is there a better way to construct this character array? (Outside of either removing -Werror or adding -Wno-narrowing).

推荐答案

因此C ++ 11对于 integer 类型和 unscoped枚举对于在promtion后适合目标类型的常量表达式,即草案C ++ 11标准部分8.5.4 [dcl.init.列表] 说:

So C++11 has an exception for integer types and unscoped enums for constant expressions that fit after promtion in the target type, the draft C++11 standard section 8.5.4 [dcl.init.list] says:

从整数类型或无作用域枚举类型到整数类型 不能代表原始类型的所有值,除了 源是一个常数表达式,其值在积分后 促销将适合目标类型.

from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.

这里的问题是,如果使用unsigned char,某些值将不适合char.

The problem here is that some of the values do not fit into char if you use unsigned char instead it should work.

clang更具帮助,因为它会警告哪些特定元素会生成警告,在这种情况下,它不会针对0x42发出警告,而针对其余部分发出警告,例如:

clang is a little more helpful in that it warns which specific elements generate the warning and in this case it does not warn for 0x42 but does for the rest, for example:

error: constant expression evaluates to 222 which cannot be narrowed to type 'char' [-Wc++11-narrowing]
char expected[] = {0x42, 0xde, 0xad, 0xbe, 0xef};
                         ^~~~

这篇关于创建字符数组,避免缩小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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