Class References

Jared Miller none at example.com
Wed Nov 20 15:06:36 PST 2013


On Monday, 28 October 2013 at 11:22:03 UTC, Jeroen Bollen wrote:
> Is it possible in D to create an enum of class references?
> Something around the lines of:
>
> enum ClassReferences : Interface {
>     CLASS1 = &ClassOne,
>     CLASS2 = &ClassTwo
> }

Here's my solution using an enum as you originally wanted. 
However, depending on what you're really trying to do, there 
could be a better way.

import std.stdio;
import std.traits : fullyQualifiedName;

interface Foo { void bar(); }

class Class1 : Foo {
	void bar() { writeln("Class1"); }
}

class Class2 : Foo {
	void bar() { writeln("Class2"); }
}

enum ClassNames : string {
	CLASS1 = fullyQualifiedName!Class1,
	CLASS2 = fullyQualifiedName!Class2
}

Foo getObj(ClassNames name) {
	// without cast, it converts to the enum member name.
	return cast(Foo)Object.factory(cast(string)name);
}

void main() {
	auto c1 = getObj(ClassNames.CLASS1);
	auto c2 = getObj(ClassNames.CLASS2);
	assert(c1 && c2);
	c1.bar();
	c2.bar();
}


More information about the Digitalmars-d-learn mailing list