Home >Backend Development >C++ >How Does C Overload Resolution Handle Value, Rvalue Reference, and Const Lvalue Reference Parameters?

How Does C Overload Resolution Handle Value, Rvalue Reference, and Const Lvalue Reference Parameters?

DDD
DDDOriginal
2024-12-01 09:40:12289browse

How Does C   Overload Resolution Handle Value, Rvalue Reference, and Const Lvalue Reference Parameters?

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

In overload resolution, it is not uncommon to encounter ambiguous calls when multiple viable functions share the same parameter type. A particularly intriguing case arises when overloading occurs between a value, an rvalue reference, and a const lvalue reference.

Ambiguity and Resolution

Given the functions:

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

the call int q = f( 3 ); becomes ambiguous. Clang and GCC prefer the rvalue reference over the lvalue reference when f( int ) is removed. However, removing either reference overload leads to ambiguity with f( int ).

Rules for Overload Resolution

Overload resolution is based on finding a unique "better match" for the parameter. In the absence of special rules, all three initializations (value, rvalue reference, and const lvalue reference) would be indistinguishable.

However, since an rvalue reference binds to an rvalue and a const lvalue reference does not, the rvalue reference is considered a better match due to the following rule in 13.3.3.2:

S1 binds an rvalue reference to an rvalue and S2 binds an lvalue reference.

This rule does not apply when one initialization is not a reference binding.

Proposal for Future Standards

The author proposes that an int && should be preferred over int in future standards because it forces an initialization binding to an initializer, unlike the unconstrained object type. This could serve as an alternative to pure pass-by-value while avoiding the overhead of moving.

The above is the detailed content of How Does C Overload Resolution Handle Value, Rvalue Reference, and Const Lvalue Reference Parameters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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