How to group similar member functions from different classes?

cy via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 18 11:08:43 PDT 2016


On Saturday, 18 June 2016 at 07:03:25 UTC, cy wrote:
> So how would you do it? Defining A.foo, B.foo, etc in one 
> place, and A.bar, B.bar, etc in another?

The only thing I've been able to figure is a horrible hack, where 
your member functions are something like

// off in define_foos.d

template foo_for(T) {
   static if(is(T == A)) {
     enum foo_for = q{
       int foo () {
         return bar+42;
       }
     };
   } else static if(is(T == B)) {
     enum foo_for = q{
       int foo () {
         return bar+23;
       }
    };
   }
}

// in classes.d

import define_foos: foo_for;

struct A {
	int bar;
	mixin(foo_for!A);
}

struct B {
	int bar;
	mixin(foo_for!B);
}

// etc

void main() {
	import std.stdio;
	A a = A(0);
	B b = B(1);
	writeln(b.foo());
	writeln(a.foo());
}


More information about the Digitalmars-d-learn mailing list