Dynamic method example in TDPL
Stanislav Blinov
blinov at loniir.ru
Fri Aug 20 03:48:17 PDT 2010
20.08.2010 13:00, Joel Christensen wrote:
There seem to be quite a few errors in this one:
> /**
> 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, /*was: Args*/Args...)(/*was: Args
> args...*/Args args) { // There should've been variadic template
> instead of variadic function
> Variant[] packedArgs = new Variant[args.length];
> foreach (i, arg; args) {
> packedArgs[i] = Variant(arg);
> }
> return call(m, /*was: args*/packedArgs); // args was used
> instead of packedArgs
> }
> }
>
> void main() {
> auto obj = new Dynamic;
> obj.addMethod("sayHello",
> delegate Variant(Dynamic, Variant[]...) { // delegate keyword
> was missing, and it wasn't matching DynMethod signature
> writeln("Hello, world!");
> return Variant();
> });
> obj.sayHello(); // Prints "Hello, world!"
> }
Maybe Andrej can add this one to errata too? :)
More information about the Digitalmars-d-learn
mailing list