c++ - C++中的整数提升和整数转换有什么区别

标签 c++ implicit-conversion integer-promotion

C++ 标准的第 4.5 节(整数提升)讨论了将整数类型转换为具有更高级别的类型的具体情况。

C++ 标准的第 4.7 节(整数转换)以(项目符号 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.5 中描述的转换(可能除了项目符号 4.5.3(枚举))可以单独使用 4.7 部分中的技术来执行:4.5.1 和 4.5.2 完全包含在 4.7 中。 1; 4.5.4 包含在 4.7.4 中。那么整个 4.5 节的目的是什么?它启用了哪些额外的转换?也许我缺少一些限制?

附言我正在阅读标准的 C++03 版本。

最佳答案

认为区别很重要,因为两者不属于相同的转换类别并且具有不同的排名(参见 13.3.3.1 .1,标准转换序列)。在重载决议方面,排名有所不同:

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 之间的区别使得以下代码没有歧义:

#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 是一次转换(因此有转换等级)

最后,这段代码调用了 foo(int),因为它是一个更好的候选者。

关于c++ - C++中的整数提升和整数转换有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4640543/

相关文章:

c++ - 运算符 T() 未在赋值中使用

c++ - 对自定义对象的 vector 进行排序

c++ - 3度转码帧I420 RGBA BGRA

c++ - Unresolved includes in eclipse CDT 其中路径名不准确

c++ - CMake 添加不区分大小写的源文件

c++ - 类对象到字符串的隐式转换运算符

c# - C# 中 casting/conversion int/double 的解释

无符号整数加法可以调用未定义的行为吗?

c++ - 用提升解释整数比较

c - C 中的整数提升示例