C++ Logo

std-discussion

Advanced search

Re: A Idea: Friend with Conditions

From: Jennifier Burnett <jenni_at_[hidden]>
Date: Sat, 21 Jun 2025 18:22:47 +0100
Second this. If you need an arbitrary (unknown and thus unnameable at time of authoring) class that meets some conditions to be able to access the internals of a class then you have a design problem.

The idea that one might have a class that is both tightly coupled to another class to the point of needing to break encapsulation to allow it access to the class' internals but also can't name directly name the type that it's tightly coupled to seems like a very odd situation to be in to me, and not one I see a huge amount of (positive) value in modifying the core language to ergonomically support.

On 21 June 2025 17:52:17 BST, Chris Ryan via Std-Discussion <std-discussion_at_[hidden]> wrote:
>Not in response to just this post but all trying to modify friends & access.
>
>The idea is we should be making the language simpler, not more complex.
>If you are trying to give partial access to part of your class, you have a
>design problem.
>Too many divergent features in one class (failed cohesiveness). Break it
>up. Move it around.
>
>In general, using 'friend' is a code smell for anti-enpasilization and a
>weak design, (you left the backdoor open)
>IMHO, One of the few valid uses is for hidden friends (ADL operator
>overloading).
>
>
>On Sat, Jun 21, 2025 at 3:15 AM SD SH via Std-Discussion <
>std-discussion_at_[hidden]> wrote:
>
>> How about adding conditions for friend?
>> Like this (or other?):
>>
>> class B { };
>> class E
>> {
>> int i;
>> E(int i) : i(i) { }
>> };
>> class A
>> {
>> static int i = 0;
>> friend typename T if(std::is_base_of<B, T>::value); // if a class
>> derived from B, it is a friend class of A
>> friend E if(std::is_default_constructible<E>::value); // E is not a
>> friend class of A because std::is_default_constructible<E>::value == false
>> };
>> class C : B
>> {
>> public:
>> int geti()
>> {
>> return A::i; // OK, because std::is_base_of<B, C>::value == true
>> }
>> };
>> class D
>> {
>> public:
>> int geti()
>> {
>> return A::i; // Error, because std::is_base_of<B, D>::value ==
>> false
>> }
>> };
>>
>> A Probably Syntax:
>> friend <type-id> if/*constexpr*/(<constexpr-bool-expression>);
>>
>> It may be a useful syntax feature.
>>
>> E. S. Himers
>> 2025/06
>> --
>> Std-Discussion mailing list
>> Std-Discussion_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>>

Received on 2025-06-21 17:22:59