Map type to class instance at compile-time

pontius via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Oct 27 11:33:01 PDT 2016


On Wednesday, 26 October 2016 at 18:19:33 UTC, Ali Çehreli wrote:
> There are different approaches but I think the solution above 
> achieves what you want:
>
> DefaultManager!(A) is managing an object of A
> DefaultManager!(B) is managing an object of B
> SomeCustomManager is managing an object of C
>
> Ali

Thanks, your solution does work! I am still not familiar with 
mixins and haven't though about using them.
I refactored it so that it accepts a manager instance:

template ManagerRegistrationFor(T, alias mgr) {
     typeof(mgr) thisComponentMgr;

     static this() {
         thisComponentMgr = mgr;
     }

     void manage(T obj) {
         thisComponentMgr.manage(obj);
     }
}

struct GlobalManager {
     void process(T)(T t) {
         manage(t);
     }
}

GlobalManager globalManager;

mixin ManagerRegistrationFor!(A, new ManagerA());
const ManagerB mgrB = new const ManagerB();
mixin ManagerRegistrationFor!(B, mgrB);
mixin ManagerRegistrationFor!(C, new ManagerC());


I have an issue with incapsulating this code in another module, 
though. I should have probably clarified that Managers can be 
defined both inside my library and in separate modules by my 
library users. If I move template ManagerRegistrationFor and 
struct GlobalManager to e.g. manager.d and attempt to define 
ManagerA,B,C and call ManagerRegistrationFor(...) in main.d, it 
doesn't compile:

1) Error: template instance manager.GlobalManager.process!(A) 
error instantiating
This happens 3 times in main.d at globalManager.process(a); and 
the other to .process calls.
2) Error: undefined identifier 'manage', did you mean module 
'manager'?
This error points to the body of GlobalManager.process in 
manager.d (it also occurs 3 times).

What would be the right way to incapsulate this mixin and 
GlobalManager to a separate module?


More information about the Digitalmars-d-learn mailing list