C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Method/member granular friendship

From: Francesco Pretto <ceztko_at_[hidden]>
Date: Wed, 27 Nov 2024 18:01:18 +0100
On Thu, 14 Nov 2024 at 08:47, Halalaluyafail3 via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> > Yes, that post seems to suggest improving granularity for friendship
> > declarations. In particular:
> >
> > class A {
> > int x = 0;
> > int y = 0;
> > friend [[selective_access(x)]] class B; // access of x only
> > };
> >
> > Should be the proposed syntax to handle my use case. Still, a bit
> > problematic in presence of overloads: maybe a per member attribute
> > would be a better pick, even though more verbose in some cases (eg.
> > declaring the friendship with the same external class for many
> > members).
>
> I think you can achieve something like this by creating separate classes for the
> members which can each individually use friend:
>
> #include<iostream>
> class X{
> friend struct A;
> int x;
> };
> class Y{
> friend struct A;
> friend struct D;
> int y;
> };
> struct A:X,Y{
> A(){
> x=1;
> y=2;
> }
> };
> struct D{
> static void test(){
> A a;
> std::cout<<a.x<<'\n';//invalid
> std::cout<<a.y<<'\n';//OK
> }
> };
>
> x and y are now in classes that can selectively choose which other classes and
> functions have access.
>

No, as said I won't use any pattern-like solution, as it implies a
maintenance cost and risk to break API/ABI in case of later changes of
the intended accessibility. This is really a problem that should be
solved in the language, as other languages have done it already.

Cheers,
Francesco

Received on 2024-11-27 17:01:33