C++ 中函数重载的歧义 Vs Java

Ambiguity in Function overloading in C++ Vs Java

在C++中的函数重载的情况下,我们知道在实际和形式参数不匹配方面可能会出现歧义。所以有一个机制来解决这个问题。

For every actual parameter P, Si be the set of corresponding formal parameters that matches best. then S will be the intersection of all Si.

为此,有 4 种类型的规则。

  1. 精确匹配
  2. 晋升
  3. 标准转换
  4. 用户定义的转换
  5. 省略号(所有人都不考虑)

Java 是否也发生类似的过程? 由于函数重载的规则在 Java 的情况下是相同的,这些类型的歧义可以采取也放在这里

类似的过程?好吧,取决于“相似”是什么意思。

但是在 Java 语言规范中有详细记录,
15.12 Method Invocation Expressions
章 尤其是子章节 15.12.2. Compile-Time Step 2: Determine Method Signature.

The process of determining applicability begins by determining the potentially applicable methods (§15.12.2.1).

The remainder of the process is split into three phases, to ensure compatibility with versions of the Java programming language prior to Java SE 5.0. The phases are:

  1. The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

  2. The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.

  3. The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.

Deciding whether a method is applicable will, in the case of generic methods (§8.4.4), require an analysis of the type arguments. Type arguments may be passed explicitly or implicitly. If they are passed implicitly, bounds of the type arguments must be inferred (§18 (Type Inference)) from the argument expressions.

If several applicable methods have been identified during one of the three phases of applicability testing, then the most specific one is chosen, as specified in section §15.12.2.5.

15.12.2.5 Choosing the Most Specific Method章总结得很好:

The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

当然比那个复杂一点