What's the difference between integer promotions and integer conversions in C++

梦想的初衷 提交于 2019-12-21 16:55:23

问题


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

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.

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. I'm reading C++03 version of the standard.


回答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.

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));
}
  • short to int is a promotion (thus having promotion rank)
  • short to unsigned short is a conversion (thus having conversion rank)

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




回答2:


Promotions occur during arithmetic and other operations. Conversions occur when merely storing one integral type inside another.



来源:https://stackoverflow.com/questions/4640543/whats-the-difference-between-integer-promotions-and-integer-conversions-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!