Getting object members

Szymon Gatner noemail at gmail.com
Thu Jun 13 03:21:41 PDT 2013


Thanks a lot Adam, this is what I came with:

module main;

import std.stdio;

class MyObject
{
   abstract string[] getPublicMembers();
}

class MyClassBase(T) : MyObject
{
   override string[] getPublicMembers()
   {
     return generatePublicMembers!T();
   }

   string[] generatePublicMembers(T)()
   {
     string[] ret;
     foreach(mem; __traits(derivedMembers, T))
     {
       static if (is(typeof(__traits(getMember, T.init, mem))))
       {
         enum prot = __traits(getProtection, __traits(getMember, 
T.init, mem));
         static if (prot == "public")
         {
           ret ~= mem;
         }
       }
     }
     return ret;
   }
}


class Foo : MyClassBase!Foo
{
   public int x;
   protected int y;
   private int p;
}

class Bar : MyClassBase!Bar
{
   int x, y;
   private int p;
}

int main(string[] argv)
{
   MyObject f = new Foo();
   MyObject b = new Bar();

   auto members = f.getPublicMembers();

   foreach (mem; members)
   {
     writeln(mem);
   }

   return 0;
}

what do you think? A question: can a mixin method be an override 
or abstract method?



More information about the Digitalmars-d-learn mailing list