Dynamic method example in TDPL

Joel Christensen joelcnz at gmail.com
Fri Aug 20 02:00:46 PDT 2010


I've typed this example program in, but it doesn't compile. I looked up 
the The D programming language errata but it wasn't listed. I'm using 
DMD v2.048.

 >>
/**
	Date: Aug 20, 2010
	This was copied from TDPL book pages 386 - 387
*/
module dynamicmethods;

import std.stdio;
import std.variant;

alias Variant delegate(Dynamic self, Variant[] args...) DynMethod;

class Dynamic {
	private DynMethod[string] methods;
	void addMethod(string name, DynMethod m) {
		methods[name] = m;
	}
	void removeMethod(string name) {
		methods.remove(name);
	}
	// Dispatch dynamically on method
	Variant call(string methodName, Variant[] args...) {
		return methods[methodName](this, args);
	}
	// Provide syntactic sugar with opDispatch
	Variant opDispatch(string m, Args)(Args args...) {
		Variant[] packedArgs = new Variant[args.length];
		foreach (i, arg; args) {
			packedArgs[i] = Variant(arg);
		}
		return call(m, args);
	}
}

void main() {
	auto obj = new Dynamic;
	obj.addMethod("sayHello",
		Variant(Dynamic, Variant[]) { //#error here. (found '{' expecting ','
			writeln("Hello, world!");
			return Variant();
		});
	obj.sayHello(); // Prints "Hello, world!"
}
<<


More information about the Digitalmars-d-learn mailing list