digitalmars.D.learn - how to get UDA only for methods
- test (24/24) Oct 16 2018 I need get the Route UDA only for method without (static methods,
- Stanislav Blinov (55/58) Oct 17 2018 1) Note that __traits(allMembers, T) gets you a tuple of names,
I need get the Route UDA only for method without (static methods, property, constructor, destructor), dont know how to do it. Route[] getRoutes(T)(){ Route[] routes; foreach(int i, m; __traits(allMembers, T) ){ pragma(msg, m.stringof); static foreach(int j, r; getUDAs!(m, Route) ) { routes ~= r; } } return routes; } struct App { Route("/index") void home(){ } Route("/blog") void blog(){ } }
Oct 16 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(){} }
Oct 17 2018