Templating Function Names

Bryce Kellogg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Dec 8 10:21:22 PST 2016


Say I've got a bunch of classes that inherit from a common 
interface (in this case Component) and a class Foo that can 
handle any subclass of Component. Like so:

interface Component { ... }
class A : Component { ... }
class B : Component { ... }
class C : Component { ... }

class Foo {
     alias a = this.of!A;
     alias b = this.of!B;
     alias c = this.of!C;
     void of(T : Component)(T t) { ... }
}

It's pretty trivial to access a specific component using regular 
templates:

     f.of!A = new A();
     f.of!B = new B();
     f.of!C = new C();

And I can alias the instantiations of these templates as seen 
above for a cleaner interface:

     f.a = new A();
     f.b = new B();
     f.c = new C();

However, suppose I have the following situation:

void main() {
     Foo f = new Foo();
     class D : Component { ... }

     f.of!D = new D(); // works fine
     f.d = new D();    // fails to compile (for obvious reason)
}

Is there a way I can get a function of Foo named after D (like 
f.d() or f.D()) without knowing before hand every single subclass 
of Component and adding aliases manually?

For example, is there a way to template the name of the function 
or an alias like:

void T(T : Component)(T t) { ... }
or
alias T = this.of!T;

Both of these just gave me functions named T.

The important thing is that it's transparent to the person 
creating a new subclass of Component. It should look like Foo 
always had a property named after their custom Component.

Is this possible?

Thanks!
Bryce



More information about the Digitalmars-d-learn mailing list