Dynamic method example in TDPL

Andrej Mitrovic andrej.mitrovich at gmail.com
Fri Aug 20 04:49:55 PDT 2010


You mean Andrei?

P.S. anyone can edit the errata page. It has a history backup, so if someone accidentally screws up something you can roll back to a previous version. If you find something that needs to be added, go ahead and do it.

Btw., I haven't reached that page yet. :p

Stanislav Blinov Wrote:

>   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