Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify rule S2807: Add a longer explanation of the hidden friend pattern #4007

Merged
merged 3 commits into from
Jun 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion rules/S2807/cfamily/rule.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,23 @@ This rule raises issues for overloaded binary mathematical and relational operat
== Why is this an issue?

When overloading binary or relational operators, it is recommended that they be declared hidden friends of the class.
A hidden friend, i.e. a friend function defined in the class body, provides the following benefits:

=== The hidden friend pattern

The hidden friend pattern consists of declaring and defining a function directly as a friend inside the class body. This reduces the function's visibility to argument-dependent lookup only. Approximately, such a function is considered only when called on an object of the enclosing class.

[source,cpp]
----
struct MyClass {
friend void function(MyClass const& arg) { // This function is a hidden friend of MyClass
...
}
};
----

=== Benefits of hidden friends

Using hidden friends provides the following benefits:

* in contrast to the member function, it allows conversion to be applied to both operands
* in contrast to free functions, it is considered only if one of the operands is an object of the given class
Expand Down