C++ Logo

std-proposals

Advanced search

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

From: Francesco Pretto <ceztko_at_[hidden]>
Date: Mon, 11 Nov 2024 14:06:35 +0100
On Mon, 11 Nov 2024 at 12:48, Sebastian Wittmeier via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> is your intention to improve the code (by limiting visibility or access) within your library or the outside interface.
>

Using regular class/struct friendship is already allowing me to
successfully reduce the API surface of the library from a API consumer
perspective. Improvements to granularity of friendship, or (possibly)
having a module scoped accessibility modifier would allow me to
restore intended encapsulation within library boundary. I now realize
I improperly referred to "visibility" in the previous email : yes, I
actually meant "accessibility".

> Problem: "within the library compilation boundaries, some classes tend to loose proper encapsulation"
>
> Solution B: "or (if it makes any sense at all) having an equivalent C++ module visibility modifier"
>
> Does your library comprise different (intended/possible) modules? And the current friendships span those boundaries and should be reduced? (Many small libraries would perhaps be just one module.)

Admittedly I have no first hand experience with C++ modules yet: if
and when I would start using modules, my library would probably
consist of a single module. If the C++ compiler can track usage of
symbols spanning different compilation units within the same module,
similarly to what happens in C# where the compiler can track usage of
symbols within the same assembly[1], then I believe a "module"
accessibility modifier could make sense in C++ as well, and would
provide an option to solve the "Problem". If it really can't and I'm
misunderstanding actual module capabilities, then sorry for mentioning
it as a possible language solution.

> Solution A:
>
> For the more granular friends approach without modules, this discussion could be interesting:
>
> https://groups.google.com/a/isocpp.org/g/std-proposals/c/wtkDvujmjug
>
> "Improving Friends with Attributes"
>
> Sadly the paper seems to be not available anymore at the old location.
>

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).

[1] https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/internal

Received on 2024-11-11 13:06:48