Alternative to friend functions?

ShadoLight ettienne.gilbert at gmail.com
Thu Feb 20 09:52:54 UTC 2020


On Thursday, 20 February 2020 at 08:02:48 UTC, Bienlein wrote:
> 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.

But where in that inheritance hierarchy will you slot the Spouse 
class in? You don't have multiple inheritance in D, so are you 
thinking along these lines?:

class Person {..}
class Spouse : Person {..}
class Male : Spouse {..}
class Female : Spouse {..}

That implies every Male and Female 'is a' Spouse which, feels a 
bit clunky to me.

Maybe a better design for your idea is to make Spouse an 
interface; something along these lines:
class Person {..}
interface Spouse {void engage(..);}
class Male : Person, Spouse {..}
class Female : Person, Spouse {..}

Then, as you say, the respective engage(..) implementations are 
done in the Male/Female subclass.

Maybe you can even declare a winArgument(..) method returning a 
bool in the Spouse interface.  For the Male class the 
implementation will be real easy: just return false!

[Disclaimer]: Last paragraph not to be taken seriously!


More information about the Digitalmars-d-learn mailing list