Alternative to friend functions?

Petar Petar
Tue Feb 18 12:51:37 UTC 2020


On Tuesday, 18 February 2020 at 12:43:22 UTC, Adnan wrote:
> What is the alternative to C++'s friend functions in D?
>
> module stable_matching;
>
> alias FemaleID = int;
> alias MaleID = int;
>
> class Person {
>     string name;
>     int id;
> }
>
> class Male : Person {
>     this(string name = "Unnamed Male") {
>         static int nextID = 0;
>         this.id = nextID++;
>         this.name = name;
>     }
> }
>
> class Female : Person {
>     this(string name = "Unnamed Female") {
>         static int nextID = 0;
>         this.id = nextID++;
>         this.name = name;
>     }
> }
>
> class Husband(uint N) : Male {
>     FemaleID engagedTo = -1;
>     const FemaleID[N] preferences;
>
>     this(FemaleID[N] preferences) {
>         this.preferences = preferences;
>     }
> }
>
> class Wife(uint N) : Female {
>     FemaleID engagedTo = -1;
>     const MaleID[N] preferences;
>
>     this(MaleID[N] preferences) {
>         this.preferences = preferences;
>     }
> }
>
> void engage(N)(ref Wife!N, wife, ref Husband!N husband) {
>     // Here, I want to access both husband and wife's engaged_to
> }
>
> class MatchPool(uint N) {
>     Husband!N[N] husbands;
>     Wife!N[N] wives;
> }

In D the unit of encapsulation is not class, but module, and so 
`private` only restricts access from other modules. If `engage` 
is declared in the same module as the classes, you should have no 
problems accessing their private members.

If you want to put `engage` in a different module, than you can 
use the `package` access modifier to allow all modules in a given 
package to access `package` members.


More information about the Digitalmars-d-learn mailing list