D RTTI?

Kenji Hara k.hara.pg at gmail.com
Mon Mar 5 17:15:19 PST 2012


On Monday, 5 March 2012 at 22:31:58 UTC, H. S. Teoh wrote:
>
> OK, it's a bit ugly I supopse, but I can live with that.
>
> Is there a way to tell whether or not a given class is a 
> derived class
> or not? I'm using the Serializable template to insert 
> serialize() into
> the class, and for derived classes I need to insert "override 
> void
> serialize() ..." but for the base class I have to omit 
> "override". How
> can I detect this in the template?

How about "wrapper template class"?
---------
import std.stdio;
class Serialized(T) : T
{
      // 2.059 new feature: class template constructor
      this(A...)(A args) {
          static if (is(typeof(super(args))))
              super(args);
      }
      void serialize() {
          foreach (i, name; __traits(allMembers, T)) {
              mixin("alias "~name~" Member;");
              static if (is(typeof(Member) == function))
              {}  // member function
              else static if (!is(typeof(Member)))
              {}  // has no type is member template
              else static if (is(Member))
              {}  // nested type declaration
              else
                  writefln("[%d] %s", i, name);   // field!!
          }
      }
}
class A {
      private int value;
}
class B : A {
      private string key;
      this(string s){ key = s; }
}
void main()
{
      auto a = new Serialized!A();
      a.serialize();
      writeln("----");
      auto b = new Serialized!B("hello");
      b.serialize();
}

output:
---------
[0] value
----
[0] key
[2] value


More information about the Digitalmars-d-learn mailing list