Safer casts

Yigal Chripun yigal100 at gmail.com
Tue May 13 00:11:16 PDT 2008


Dee Girl wrote:
<snip>
> 1. Is the code inside sort!() as powerful as delegate?
>
>2. Is the call inside sort direct or indirect? Thank you, Dee Girl

well, you've been answered by an expert (Thanks Sean!)
I didn't know that Walter is working on making inlining delegates
possible, that this is indeed great news. :)
to answer your questions:
as I understand it, a delegate is internally a struct with two pointers:
a context pointer and a function pointer. the context pointer has the
address of the outer function for nested functions, or the this pointer
for methods. so, when passing a delegate you pass this struct.
based on that, I think that the answer to your second question is that
the call is indirect. this is true for both cases, otherwise that trick
of using a sort!() instance inside a mySort function wouldn't work. all
you pass to the template version is just a D symbol, in our case the
name of the delegate. in both cases you need to call that delegate.
you can pass regular function pointers to the template too (they are
written either with the function reserved word, or with the C syntax)
and those are simpler to inline. you can overload a non-templated sort
function to receive those as well.
I hope, some day function pointers would be implicitly castable to
delegates (just make the context pointer contain null) and this will
remove the need for providing two identical functions (one for delegates
and one for function pointers)
btw, another way of changing the delegate for a specific sort!()
instance is simply to assign it; no need for a wrapper function.
delegate bool(int a, int b) dg;
dg = aDelegate;
sort!(dg)(array);
dg = otherDelegate;
sort!(dg)(array); // the same instance should be used.







More information about the Digitalmars-d mailing list