C ++ 11:“将转换缩小到{}"带模数 [英] C++11: "narrowing conversion inside { }" with modulus

查看:118
本文介绍了C ++ 11:“将转换缩小到{}"带模数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在启用gccC++11的情况下编译以下代码:

I try to compile the following code with gcc and C++11 enabled:

unsigned int id = 100;
unsigned char array[] = { id % 3, id % 5 };

我收到这些警告:

在{} [-Wnarrowing]

narrowing conversion of ‘(id % 3u)’ from ‘unsigned int’ to ‘unsigned char’ inside { } [-Wnarrowing]

在线观看演示

有没有一种方法可以帮助编译器找出 id%3 的结果是否适合未签名的字符?

Is there a way to help the compiler find out that the result of id % 3 fits into an unsigned char?

推荐答案

在这种特定情况下,制作id const

In this specific case making id const or constexpr will fix the problem:

constexpr unsigned int id = 100;

因为有一个恒定表达式的情况是例外,其转换后的结果将适合目标类型.

since there is an exception for the case where you have a constant expression whose result after conversion will fit into the target type.

在更一般的情况下,您还可以使用 static_cast 强制转换结果到未签名的字符:

In the more general case you may also use static_cast to cast the result to unsigned char:

{ static_cast<unsigned char>( id % 3), static_cast<unsigned char>( id % 5) }
  ^^^^^^^^^^^                          ^^^^^^^^^^^

我们可以在

We can find he exception for constant expressions and narrowing conversions in the draft C++ standard section 8.5.4 List-initialization which says:

缩小转换是隐式转换

A narrowing conversion is an implicit conversion

并包括以下项目符号(强调我的):

and include the following bullet (emphasis mine):

  • 从整数类型或非范围枚举类型到不能表示原始类型的所有值的整数类型, 源是一个常数表达式,其值在积分后 促销将适合目标类型.
  • 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.

请注意,由于 查看全文

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