C++ 重载歧义:原始类型的转换与提升

C++ overload ambiguity: conversion versus promotion with primitive types

在此代码中:

void f(float f, long int i) { cout << "1" << endl; }
void f(float f, float d) { cout << "2" << endl; }

int main() {

   f(5.0f, 5);

}

有歧义。 Check it out!。但是,第二个参数是有符号整数。将 int 绑定到 long int 参数需要升级,但绑定到 float 需要转换。

由于第一个参数与两个重载完全匹配,因此不算数。但是关于第二个参数,它在第一次重载(promotion)上的排名比在第二个(conversion)上的排名要好。

为什么会出现解析歧义,而不是选择第一个重载?

intlong 是一个转换。 shortint 是升职。 (有关积分促销的完整列表,请参阅 [conv.prom]。)

同理,floatdouble也是浮点数提升。 doublelong double 是一个转换。

因为两种情况都没有完全匹配。 5、无条件,有int类型。您的方法声明 "float" 或 "long int" 作为参数,并且 both 需要转换。长!= 整数!

5 默认为 int 类型。所以你在这两种情况下都有转化:

  • intlong int(又名 long
  • intfloat

1) longint 不兼容,因为在 certain data models 上它们的大小可能不同。

2) intfloat 的转换定义为 "Floating - integral conversions":

Integer or unscoped enumeration type can be converted to prvalue of any floating-point type. If the value can not be represented correctly, it is implementation defined whether the closest higher or the closest lower representable value will be selected.