D RTTI?

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Mar 5 15:26:01 PST 2012


On Tue, Mar 06, 2012 at 12:03:48AM +0100, Timon Gehr wrote:
> On 03/05/2012 11:33 PM, H. S. Teoh wrote:
[...]
> >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?
[...]
> 
> You can check typeof(this).

Ahh, that's what I was looking for.

Awesome!!! By combining typeof(this) with __traits(hasMember,...), I can
actually insert missing methods into a class if they haven't been
defined yet, or override existing methods if they are already defined in
the base class:

	template Serializable() {
		enum Serializable = q{
			static if (__traits(hasMember, typeof(this),
					"serializable"))
			{
				// Override existing method
				override void serialize(...);
			}
			else
			{
				// Insert missing method
				void serialize(...);
			}
		};
	}

	class A {
		// This causes A to acquire serialize()
		mixin(Serializable!());
	}

	class B : A {
		// This causes B to override serialize()
		mixin(Serializable!());
	}


D is too cool for words.


T

-- 
For every argument for something, there is always an equal and opposite argument against it. Debates don't give answers, only wounded or inflated egos.


More information about the Digitalmars-d-learn mailing list