Given three overloaded functions with varying parameter types (value, rvalue reference, const lvalue reference), a function call can become ambiguous if all three overloads are viable. This article discusses the rules governing overload resolution in such scenarios and explores the nuanced behavior observed in C .
With only one parameter to consider, the rule states that one parameter initialization must be a better match than both the other two. When comparing two initializations, either one is deemed better, or neither is considered better (indistinguishable).
In the absence of special rules for direct reference binding, the three initializations would be indistinguishable in all three comparisons. However, these special rules elevate int&& (rvalue reference) above const int& (lvalue reference), while neither is considered better or worse than int (value). Thus, there arises no best match.
This behavior is illustrated in the following matrix:
S1 S2 int int&& indistinguishable int const int& indistinguishable int&& const int& S1 better
The matrix shows that int&& is preferred over const int& based on clause 13.3.3.2 of the C standard. This rule applies to reference bindings that do not refer to implicit object parameters of non-static member functions without ref-qualifiers, and where S1 binds an rvalue reference to an rvalue while S2 binds an lvalue reference.
However, this rule does not apply when one of the initializations is not a reference binding, hence the ambiguity.
The author suggests considering int&& (rvalue reference) as a better match than int (value), as the reference must bind to an initializer while the object type is not subject to such a constraint. This could potentially create a new overload resolution rule that prioritizes binding from an initializer. However, this proposition requires further discussion and potential standardization through the isocpp future proposals platform.
The above is the detailed content of When Do C Overload Resolution Ambiguities Arise Between Value, Rvalue Reference, and Const Lvalue Reference Parameters?. For more information, please follow other related articles on the PHP Chinese website!