How to group similar member functions from different classes?

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 18 04:04:47 PDT 2016


On Friday, 15 July 2016 at 17:25:23 UTC, cy wrote:
> On Monday, 20 June 2016 at 16:39:54 UTC, Marc Schütz wrote:
>> Untested:
>
> Seems to only work if A and B are both defined in the same file 
> as Foos (defeating the purpose). Putting A and B in a.d and b.d 
> respectively gives me these errors:
>
> a.d(2): Error: undefined identifier 'Foos'
> a.d(2): Error: mixin a.A.Foos!() is not defined
> b.d(2): Error: undefined identifier 'Foos'
> b.d(2): Error: mixin b.B.Foos!() is not defined
>
> I also tried switching it around, like
> // b.d
> import foos Foos;
> class B {
>   mixin Foos;
> }
>
> but that of course gives the error:
> foos.d(4): Error: undefined identifier 'A'
> b.d(3): Error: mixin b.B.Foos!() error instantiating
>
> since you can't do a static if(typeof(this) == A) without 
> importing A from a somehow. (you can do else static 
> if(typeof(this) == B) without importing B though, since it does 
> the branch for A first)
>
> I think a mixin here is just required, because you can't use an 
> identifier before it's defined, even at compile time. Honestly, 
> I have yet to find a use for mixin templates.

It works if you add forward declarations for the classes:

import a, b;
class A;
class B;
mixin template Foos() {
     static if(is(typeof(this) == A))
     void foo() { /* implementation for A */ }
     static if(is(typeof(this) == B))
     void foo() { /* implementation for B */ }
}



More information about the Digitalmars-d-learn mailing list