Safer casts
Dee Girl
deegirl at noreply.com
Sat May 10 23:42:01 PDT 2008
BCS Wrote:
> Reply to Dee,
>
> > Yigal Chripun Wrote:
> >
> >> Dee Girl wrote:
> >>
> >>> I agree! Strings and aliases are much less powerful than delegates
> >>> and closures because they are static and can not have state.
> >>> But I am confused about something. I compiled this with phobos:
> >>> sort!(function bool(int a, int b) { return a > b; })(array);
> >>>
> >>> There is clear difference in syntax from your examples. But my
> >>> question is: what are the differences in semantics? Thank you, Dee
> >>> Girl
> >>>
> >> I'm not sure what exactly are you asking. are you asking what's the
> >> difference between a delegate and a function?
> >>
> > Please let me rephrase. What is the difference between a function
> > passed as an alias, and a delegate? You hate one and you like the
> > other so the difference must be big. But I do not find it. Thank you,
> > Dee Girl
> >
>
> a function is just a free function or a static class function or the like.
> A delegate is both a function and a context. Generally the context is another
> function's scope or an object or struct.
Sorry I do not know how to express myself. It is frustrating ^_^.
I understand what a function is. But it looks to me as when a function is passed to a template weird things happen. I have compiled and run successfully this program:
#!/home/yasuko/bin/compile-launch -w
import std.stdio;
import std.algorithm;
void main()
{
int[] array = [ 1, 2, 3, 4 ];
int x = 5;
bool comp(int a, int b) { return a + x > b + x; }
sort!(comp)(array);
writeln(array);
sort(array);
writeln(array);
test(&comp);
writeln(array);
}
void test(bool delegate(int, int) dg)
{
int[] array = [ 1, 2, 3, 4 ];
sort!(dg)(array);
}
There are many interesting things about above program. Function comp accesses a variable in its enclosing scope therefore it can not be a "simple" function. However sort works with it.
Then even more interesting. I pass the function as a delegate to another function. Here sort works again even when passed the delegate! So I see no difference between passing the delegate as a template alias or as a normal parameter. But I do not understand how the compiler can generate the code for the dynamic case. Dee Girl
More information about the Digitalmars-d
mailing list