Deduplicating template reflection code

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 14 01:55:48 PDT 2017


On Friday, 14 April 2017 at 08:24:00 UTC, Johannes Pfau wrote:
> I've got this code duplicated in quite some functions:
>
> ---------------------
> [...]1
>
>             foreach (MethodType; overloads)
>             {
> 		// function dependent code here
>             }
> [...]2
> --------------------
>
> What's the idiomatic way to refactor / reuse this code fragment?
>
> -- Johannes

Your options are at least the following two (both untested, but 
should work):

Option 1: Template Mixins

---
mixin template Foo(alias API, Dg)
{
     void foo()
     {
        [...]1
              foreach (MethodType; overloads)
              {
                 Dg(MethodType);
              }
        [...]2
     }
}

mixin Foo!(API, (MethodType) {
// function dependent code here
});
foo();
---

Option 2: Code generation using CTFE

---
string genFoo(alias API, string justDoIt)
{
     import std.array : appender;
     auto code = appender!string;
     code.put(`[...]1`);
     code.put(`foreach (MethodType; overloads) {`);
     code.put(justDoIt);
     code put(`}`);
     code.put(`[...]2`);
}

mixin(genFoo!(API, q{
     // function dependent code here
})());
---

Personally, I'd consider the second approach to be idiomatic, but 
YMMW.


More information about the Digitalmars-d-learn mailing list