Pointers to methods

nazriel spam at dzfl.pl
Sun Mar 3 19:51:05 PST 2013


On Monday, 4 March 2013 at 03:44:20 UTC, Ali Çehreli wrote:
> On 03/03/2013 07:21 PM, nazriel wrote:
>
> > *[1] - code for lazy people :
>
> Thank you very much for doing that. It is the only way to 
> ensure that these threads will remain complete.
>
> Here are two ways depending on what you need:
>
> import std.stdio;
>
> class A
> {
>     int x;
>
> public:
>     this (int y) { x = y; }
>
>     void foo()
>     {
>         writefln("::foo(), x: %s", x);
>     }
> };
>
> class B : A
> {
> public:
>     this(int y)
>     { super(y); }
> };
>
> void main()
> {
>     {
>         auto a = new A(3);
>         auto b = new B(4);
>
>         // When objects are available up front, initialize the 
> function
>         // pointer by an object:
>         auto fp = &a.foo;
>         fp();
>         fp = &b.foo;
>         fp();
>     }
>
>     {
>         // When no object is available up front, use a function 
> literal to be
>         // called with objects later on:
>         auto fp = ((A o) => o.foo());
>
>         auto a = new A(5);
>         auto b = new B(6);
>
>         fp(a);
>         fp(b);
>     }
> }
>

The 2nd one is what I was looking for.
Thanks a lot Ali.



More information about the Digitalmars-d-learn mailing list