Calling an alias for a Class method in another scope
Max Samukha
maxsamukha at gmail.com
Sat Jun 2 10:33:02 PDT 2012
On Friday, 1 June 2012 at 14:33:59 UTC, d coder wrote:
> Steve
>
> One small thing. As you said I might declare a delegate in an
> alternate
> fashion that is by saying "void delegate() dg;".
>
> But would it be possible to rewrite the following declaration
> in a way that
> avoids naming foo explicitly. I would just have an alias for
> foo. I am
> asking this to cover the cases where foo might have a list of
> arguments and
> I want to create a delegate with the same list of arguments.
>
> typeof(&F.init.foo) dg;
>
>
> Regards
> - Puneet
The language/standard library do not provide a straightforward
way of constructing a delegate type from a corresponding function
(of function pointer) type, so you will have to go hacky. It is
easiest to use std.functional.toDelegate (don't ask why it is in
std.functional):
import std.functional : toDelegate;
auto ref call(alias fn, T, A...)(T t, auto ref A args)
{
typeof(toDelegate(&fn)) dg;
dg.ptr = cast(void*)t;
dg.funcptr = &fn;
return dg(args);
}
At the moment, the ref-ness of the return type is not determined
correctly because of a compiler bug. Otherwise, that works mostly
fine.
Note, that the delegate approach comes with performance penalty,
which dmd cannot currently optimize out. So it is slower than a
direct call.
In a parallel reality D would have a separate kind of (pointers
to) functions that take a context pointer. Something like
extern(DWithContext) function(...)
Then such functions/function pointers could be made callable
directly with the context pointer as the first argument. Also, a
delegate's funcptr would be typed correctly.
More information about the Digitalmars-d
mailing list