www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Templating Function Names

reply Bryce Kellogg <kellogg uw.edu> writes:
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 

     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) { ... }
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?

Dec 08 2016
parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 12/08/2016 10:21 AM, Bryce Kellogg wrote:

 It should look like Foo always had a property named after their 
custom Component. opDispatch? https://dlang.org/spec/operatoroverloading.html#dispatch Ali
Dec 08 2016