Alternative to friend functions?
Bienlein
ffm202 at web.de
Thu Feb 20 08:02:48 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;
> }
I would make Husband and Wife subclasses of a common abstract
superclass Spouse that declares the engagedTo var. The Spouse
superclass would also be the place where to put the engage
method. What is different for males and females you can redefine
in the respective subclass.
More information about the Digitalmars-d-learn
mailing list