Pointers to methods
Ali Çehreli
acehreli at yahoo.com
Sun Mar 3 19:44:20 PST 2013
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);
}
}
Ali
More information about the Digitalmars-d-learn
mailing list