Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top