c++ - 为什么采用 int 的函数重载优于采用 unsigned char 的函数重载?

标签 c++ overloading

考虑这个程序:

#include <iostream>

using namespace std;

void f(unsigned char c) {
  cout << c << endl;
}

void f(int c) {
  cout << c << endl;
}

int main() {
  f('a');
}

这会打印出 97,表明选择的 f() 重载是采用 int 的重载。我觉得这很奇怪;直觉上 unsigned char 不是更适合 char 吗?

最佳答案

wouldn't intuitively an unsigned char be a better match for a char?

嗯,我想,但不是根据标准。根据 [conv.prom]p1 :

A prvalue of an integer type other than bool, char16_­t, char32_­t, or wchar_­t whose integer conversion rank is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; [...]

现在,这三种字符类型具有相同的等级,而有符号类型的等级总是小于int。 .这是 [conv.rank]p1.6 的组合和 [conv.rank]p1.2 :

  • The rank of a signed integer type shall be greater than the rank of any signed integer type with a smaller size.

  • [...]

  • The rank of char shall equal the rank of signed char and unsigned char.

基本上,每个字符的等级总是小于 int它们都可以用 int 表示,因此 unsigned char 的过载不是更好的匹配,因为它会涉及从 char 的转换至 unsigned char ,而不是促销。

如果您将重载更改为 char ,那么就会有一个完全匹配,因此自然会选择“正确的”重载(在您看来)。

关于c++ - 为什么采用 int 的函数重载优于采用 unsigned char 的函数重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45775764/

相关文章:

c++ - 我需要一个树转储选项,它在当前的 gcc 版本中不再存在

c++ - 在 C++ 中展平 3D 数组以与 MPI 一起使用

C++在运行时从集合中选择类型

c++ - 使用 vector 随机洗牌

c++ - 谷歌模拟 : Mocked overloaded functions create warning C4373

c++ - 修改 std::vector 函数(继承?)

c++ - "predefine"和使用命名空间和 std::shared_ptr 的正确方法是什么?

c++ - 右值参数无法在函数重载中解析

c++ - 模板化类然后重载运算符 (C++)

c++ - 为什么 GCC 不能消除多个继承函数的歧义(但 clang 可以)?