Home > Backend Development > C++ > Why is Overload Resolution Ambiguous Between `int`, `int&&`, and `const int&`?

Why is Overload Resolution Ambiguous Between `int`, `int&&`, and `const int&`?

Mary-Kate Olsen
Release: 2024-11-29 00:04:15
Original
787 people have browsed it

Why is Overload Resolution Ambiguous Between `int`, `int&&`, and `const int&`?

Overload Resolution between Value, Rvalue Reference, and Const Lvalue Reference

Consider the following scenario:

int f( int );
int f( int && );
int f( int const & );

int q = f( 3 );
Copy after login

Calling f(3) results in an ambiguous overload resolution. Eliminating f( int ) causes Clang and GCC to prioritize the rvalue reference over the lvalue reference. However, removing either reference overload leads to ambiguity with f( int ).

Overload Resolution Rules

Overload resolution typically follows a strict partial ordering. However, in this case, int appears to be equivalent to two concepts that are not equivalent to each other. The specific rules governing this situation are as follows:

  • At least one parameter initialization for the parameter in question must be a better match than both other two.
  • When comparing two initializations, either one is better than the other, or neither is better (they are indistinguishable).
  • Without specific rules for direct reference binding, all three initializations in this scenario would be indistinguishable.
  • Direct reference binding rules make int && a better match than const int &, but neither is better or worse than int.

Special Case: Reference Binding

13.3.3.2 of the C standard provides a special rule for direct reference binding:

If S1 and S2 are reference bindings (8.5.3) and neither refers to an implicit object parameter of a non-static member function declared without a ref-qualifier, and S1 binds an rvalue reference to an rvalue and S2 binds an lvalue reference, then S1 is a better match than S2.

This rule does not apply when one of the initializations is not a reference binding.

Future Considerations

The idea of making reference bindings a better match than non-reference bindings has been proposed. To initiate discussions on this topic, it is recommended to post such proposals to the ISO C Future Proposals forum.

The above is the detailed content of Why is Overload Resolution Ambiguous Between `int`, `int&&`, and `const int&`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template