C++ Logo

std-discussion

Advanced search

Re: A Idea: Friend with Conditions

From: Tiago Freire <tmiguelf_at_[hidden]>
Date: Sat, 21 Jun 2025 15:46:04 +0000
I'm not convinced about the particular syntax.

But let's say we have the following:

public(T, is_derived_from<T, unit_test>):

now I don't need compromise the class in order to evaluate internal states in unit tests.

let's say that you have an interface class that interacts with "bar" like objects and "foo" type objects but I don't want "foo" to interact with "bar" interfaces and I don't want "bar" to interact with "foo" interfaces... this would be very useful.




________________________________
From: Std-Discussion <std-discussion-bounces_at_lists.isocpp.org> on behalf of Jason McKesson via Std-Discussion <std-discussion_at_[hidden]>
Sent: Saturday, June 21, 2025 3:43:30 PM
To: std-discussion_at_[hidden]g <std-discussion_at_[hidden]>
Cc: Jason McKesson <jmckesson_at_[hidden]>
Subject: Re: [std-discussion] A Idea: Friend with Conditions

On Sat, Jun 21, 2025 at 6:15 AM SD SH via Std-Discussion
<std-discussion_at_[hidden]cpp.org> 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.

OK: *how* would it be useful? Why would you want a class to be a
friend just because that class has a default constructor, or is a base
class of something? Where would this stuff actually be useful?

Also, what is `T` in the above example? Was there supposed to be a
template header somewhere?
--
Std-Discussion mailing list
Std-Discussion_at_[hidden]
https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion

Received on 2025-06-21 15:46:11