Calling an alias for a Class method in another scope

Steven Schveighoffer schveiguy at yahoo.com
Fri Jun 1 05:39:59 PDT 2012


On Fri, 01 Jun 2012 08:32:02 -0400, d coder <dlang.coder at gmail.com> wrote:

> Hello All
>
> Particularly I would like to know if it is possible at all in D to  
> invoke a
> class method transferred to a scope outside the class as an alias  
> argument.

Is it possible?  Yes.  But not easy.  I won't go into the details, but  
suffice to say, you must reconstruct a delegate and then call it.

D does not have "pointers to members" like C++ does.  So when you alias  
f.foo you are actually aliasing the function F.foo (without the context  
pointer, and without a parameter to be able to place it).

However, there is another way -- use delegates:

void main() {
   Foo f = new Foo();
   auto dg = &f.foo; // need to make a symbol so it can be aliased
   callfoo!(dg)();
}

Sorry if this is disappointing, D is not as low-level in this area.  But  
if you are willing to always pair a member function with its context  
pointer, delegates are much simpler and more useful than pointers to  
members:

void main() {
    Foo f = new Foo;
    auto dg = &f.foo;
    dg();
}

-Steve


More information about the Digitalmars-d mailing list