C ++中整数提升和整数转换之间有什么区别 [英] What's the difference between integer promotions and integer conversions in C++

查看:101
本文介绍了C ++中整数提升和整数转换之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准的第4.5节(整数提升)讨论将整数类型转换为具有更高等级的类型的特定情况.

Section 4.5 of the C++ standard (integer promotion) talks about specific cases of converting integral types to types with a higher rank.

C ++标准的4.7节(积分转换)以(项目符号4.7.1)开头:

Section 4.7 of the C++ standard (integral conversions) begins with (bullet 4.7.1):

可以将整数类型的右值转换为另一种整数类型的右值.枚举类型的右值可以转换为整数类型的右值.

An rvalue of an integer type can be converted to an rvalue of another integer type. An rvalue of an enumeration type can be converted to an rvalue of an integer type.

据我所知,可以仅使用4.7节中的技术来执行4.5中描述的转换(也许除了项目符号4.5.3(枚举)):4.7完全覆盖了4.5.1和4.5.2. 1; 4.5.4被4.7.4覆盖.那么整个4.5节的目的是什么?它还能实现哪些其他转换?也许我错过了一些限制?

As far as I understand conversions described in 4.5 (maybe except for the bullet 4.5.3 (enums)) can be performed by using the techniques from 4.7 section alone: 4.5.1 and 4.5.2 are completely covered by 4.7.1; 4.5.4 is covered by 4.7.4. So what's the purpose of the entire 4.5 section? What additional conversions does it enable? Maybe I'm missing some restrictions?

P.S.我正在阅读标准的C ++ 03版本.

P.S. I'm reading C++03 version of the standard.

推荐答案

认为区别很重要,因为两者都不属于相同的转化类别不同的 rank (请参见13.3.3.1.1,标准转换顺序).在超载分辨率方面,排名有所不同:

I think that the distinction is important because both do not fall in the same conversion category and have different rank (see 13.3.3.1.1, Standard conversion sequences). The rank makes a difference when it comes to overload resolution :

标准转化顺序按其排名排序:完全匹配"比促销"更好, 比转化更好.

Standard conversion sequences are ordered by their ranks: an Exact Match is a better conversion than a Promotion, which is a better conversion than a Conversion.

最后,我相信正是4.5和4.7之间的区别使以下代码变得明确:

In the end, I believe it is the distinction between 4.5 and 4.7 that makes the following code unambiguous :

#include <iostream>

void foo(int i)            { std::cout << "foo(int)" << std::endl; }
void foo(unsigned short i) { std::cout << "foo(unsigned short)" << std::endl; }

int main()
{
    foo(static_cast<short>(1));
}

  • shortint是升迁(因此具有升迁等级)
  • shortunsigned short是一次转化(因此具有转化排名)
    • short to int is a promotion (thus having promotion rank)
    • short to unsigned short is a conversion (thus having conversion rank)
    • 最后,此代码调用foo(int),因为它是更好的候选者.

      In the end, this code calls foo(int) because it is a better candidate.

      这篇关于C ++中整数提升和整数转换之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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