introspection woes (2)

Robert Clipsham robert at octarineparrot.com
Mon Jun 13 06:23:28 PDT 2011


On 13/06/2011 13:56, Lloyd Dupont wrote:
> Thanks Robert!
>
> Mm.. can you (per chance!) share some code?
> I'm a newbie and compile time reflection is something which eludes me
> (so far...)!

See: http://www.digitalmars.com/d/2.0/traits.html
----
class MyClass
{
     void method1(){}
     void method2(){}
}

import std.stdio;

void main()
{
     foreach (member; __traits(allMembers, MyClass))
         writefln("member: %s", member);

     foreach (member; __traits(derivedMembers, MyClass))
         writefln("derived member: %s", member);
}
----

Instead of writefln() you can append to an array. You can also make this 
a bit more generic with:
----
class MyClass
{
     mixin memberArray!MyClass;
     void method1(){}
     void method2(){}
}

import std.stdio;

mixin template memberArray(T)
{
     immutable static members = [__traits(derivedMembers, T)];
}

void main()
{
     foreach (member; MyClass.members)
         writefln("member: %s", member);
}
----

Hope this helps :)

-- 
Robert
http://octarineparrot.com/


More information about the Digitalmars-d-learn mailing list