Deduplicating template reflection code

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 14 06:41:45 PDT 2017


On Friday, 14 April 2017 at 11:29:03 UTC, Johannes Pfau wrote:
>
> Is there some way to wrap the 'type selection'? In pseudo-code 
> something like this:
>
> enum FilteredOverloads(API) = ...
>
> foreach(Overload, FilteredOverloads!API)
> {
>     ....
> }

Sure, but that's a bit more complex:

---
[...] // IgnoreUDA declaration
[...] // isSpecialFunction declaration

///
template FilteredOverloads(API)
{
     import std.traits : hasUDA, isSomeFunction, 
MemberFunctionsTuple;
     import std.meta : staticMap;
     import std.typetuple : TypeTuple;

     enum derivedMembers = __traits(derivedMembers, API);

     template MemberOverloads(string member)
     {
         static if (__traits(compiles, __traits(getMember, API, 
member)))
         {
             static if (isSomeFunction!(__traits(getMember, API, 
member))
                        && !hasUDA!(__traits(getMember, API, 
member), IgnoreUDA)
                        && !isSpecialFunction!member) {
                 alias MemberOverloads = 
MemberFunctionsTuple!(API, member);
             } else {
                 alias MemberOverloads = TypeTuple!();
             }
         } else {
             alias MemberOverloads = TypeTuple!();
         }
     }

     alias FilteredOverloads = staticMap!(MemberOverloads, 
derivedMembers);
}

//pragma(msg, FilteredOverloads!API);
foreach(Overload; FilteredOverloads!API) {
     // function dependent code here
}
---

Nested templates and std.meta are your best friends if this is 
the solution you prefer :)


More information about the Digitalmars-d-learn mailing list