Home > Backend Development > C++ > How Does C Overload Resolution Handle `int`, `int&&`, and `const int&`?

How Does C Overload Resolution Handle `int`, `int&&`, and `const int&`?

Patricia Arquette
Release: 2024-11-20 19:58:16
Original
338 people have browsed it

How Does C   Overload Resolution Handle `int`, `int&&`, and `const int&`?

Overload Resolution between Value, Rvalue Reference, Const Lvalue Reference

Consider the following function overloads:

int f( int );
int f( int && );
int f( int const & );
Copy after login

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:

  • int from 3
  • int&& from 3
  • int const& from 3

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!

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