advanced function binding

Kirk McDonald kirklin.mcdonald at gmail.com
Thu Mar 29 02:57:34 PDT 2007


Moritz Warning wrote:
> Hi,
> 
> thank you again!
> I wasn't aware that the delegate can accept a ParameterTypeTuple
> and the difference between the function type declarations.
> Something I have learned, nice. :)
> 
> Anyway, one probably small problem remains; when I try to compile your code I get:
> 
> Main.d:94: Error: this for getBar needs to be type Foo not type Main.Wrapper!(Foo,getBar).Wrapper
> Main.d:94: Error: cannot implicitly convert expression (&this.getBar) of type void delegate(()) to void(*)()
> Main.d:65: template instance Main.Wrapper!(Foo,getBar) error instantiating
> 
> line 94 is "dg.funcptr = &Func;"
> line 65 is "Wrapper!(Foo, Foo.getBar) x = new Wrapper!(Foo, Foo.getBar)();"
> 
> It seems to me the compiler assumes the base class of &Func is not Foo, but the surrounding object?! - weird.
> I got rid of the second error adding cast(void(*)()), but it also leaves a bad feeling. :P
> 

Oh! I've seen this before. When you take the address of a member 
function, any member function, even one of an unrelated class, from 
inside a class, the compiler wants to take it as a delegate with 'this' 
as the context. It then complains that 'this' is of the wrong type, as 
you see in the first error. For a better feeling, try cast(FuncPtr) instead.

One other thing: You can re-write that assignment using D's type 
inference. You can also drop the trailing parentheses.

auto x = new Wrapper!(Foo, Foo.getBar);

Isn't that much better? :-)

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list