how to get UDA only for methods

Stanislav Blinov stanislav.blinov at gmail.com
Wed Oct 17 07:15:57 UTC 2018


On Wednesday, 17 October 2018 at 02:54:26 UTC, test wrote:
> I need get the Route UDA only for method without (static 
> methods, property, constructor, destructor), dont know how to 
> do it.

1) Note that __traits(allMembers, T) gets you a tuple of names, 
not actual member aliases.
2) Remember there may be overloads
3) Filter the unwanted out:

import std.traits;
import std.meta : Alias, AliasSeq;
import std.stdio;
import std.string : startsWith;
import std.algorithm : among;

alias operatorNames = AliasSeq!("opUnary", "opIndexUnary", 
"opCast", "opBinary", "opBinaryRight",
                                 "opIn", "opIn_r", "opEquals", 
"opCmp", "opCall", "opAssign",
                                 "opIndexAssign", "opOpAssign", 
"opIndexOpAssign", "opSliceOpAssign",
                                 "opIndex", "opSlice", "opDollar", 
"opDispatch");

void main() {
     writeln(getRoutes!App);
}

struct Route { string r; }

Route[] getRoutes(T)(){
     Route[] routes;
     foreach (name; __traits(allMembers, T)) {
         alias member = Alias!(__traits(getMember, T, name));
         static if (__traits(isStaticFunction, member) ||
                    name.startsWith("__")              ||
                    name.among(operatorNames))
         {}
         else static if (is(typeof(member) == function)) {
             foreach (overload; __traits(getOverloads, T, name)) {
                 pragma(msg, name);
                 static foreach(route; getUDAs!(overload, Route)) {
                     routes  ~= route;
                 }
             }
         }
     }
     return routes;
}

struct App {

     @Route("xxx")
     int field;

     @Route("/blah")
     this(this) {}

     @Route("ggg")
     ~this() {}

     @Route("/index")
     void home() {}

     @Route("/index2")
     void home(bool overloaded) {}

     @Route("/blog")
     void blog(){}
}



More information about the Digitalmars-d-learn mailing list