Overload Resolution Ambiguity in Presence of Value, Rvalue Reference, and Const Lvalue Reference Overloads
In C , when a function call involves multiple viable overloads, overload resolution determines the best match based on a strict partial ordering. However, certain scenarios introduce ambiguity, as exemplified by the following code:
int f( int ); int f( int && ); int f( int const & ); int q = f( 3 );
While this call is ambiguous, removing f( int ) causes both Clang and GCC to favor the rvalue reference overload f( int && ) over the lvalue reference f( int const & ). However, removing either reference overload leads to ambiguity with f( int ).
Rules of Overload Resolution
In overload resolution, a parameter initialization within a function call must be a better match than both the other initializations. When comparing two initializations, one may be better, indistinguishable, or worse. In the given scenario, the special rules for direct reference binding make int && better than const int &, but neither is better or worse than int. Therefore, no best match exists.
Special Rule for Rvalue References
Intriguingly, the rule that favors rvalue references over lvalue references only applies when both initializations involve reference bindings. However, when one initialization is a non-reference binding, as in the case of int, this rule does not apply.
Possible Future Extensions
The proposal to prioritize int && over int in overload resolution aims to provide a more efficient mechanism for handling ownership. By binding the reference to an initializer, this approach ensures that the object is owned and can be manipulated directly, potentially eliminating the overhead of copying.
The above is the detailed content of Why is Overload Resolution Ambiguous Between `int`, `int&&`, and `const int&` in C ?. For more information, please follow other related articles on the PHP Chinese website!