Overload Resolution between Value, Rvalue Reference, Const Lvalue Reference
Consider the following function overloads:
int f( int ); int f( int && ); int f( int const & );
The call int q = f( 3 ); is ambiguous because all three overloads are viable for the argument. The rules for overload resolution state that there must be one parameter initialization that is better than both of the others.
In this case, the parameter initializations are:
However, none of these initializations is better than the other two. Therefore, the call is ambiguous.
Removing f( int ) causes Clang and GCC to prefer the rvalue reference (int&&) over the lvalue reference (int const&). This is because the rvalue reference can be bound to the rvalue 3, while the lvalue reference cannot. Removing either reference overload results in ambiguity with f( int ).
This behavior is due to the fact that int is equivalent to both int&& and int const&. However, int&& and int const& are not equivalent to each other. The rule for choosing between them is that int&& is better than int const& when both are reference bindings and int&& binds to an rvalue and int const& binds to an lvalue.
This rule does not apply when one of the initializations is not a reference binding. Therefore, int is indistinguishable from both int&& and int const&.
There is no chance that int&& will be preferred over int in a future standard. The proposed rule would make a reference binding a better match than a non-reference binding, which would go against the existing rules for overload resolution.
The above is the detailed content of How Does C Overload Resolution Handle `int`, `int&&`, and `const int&`?. For more information, please follow other related articles on the PHP Chinese website!