October 21, 2002 Problems with delegates | ||||
|---|---|---|---|---|
| ||||
This code works:
alias void delegate(int) t_func;
class Foo
{
t_func func1;
void dothis()
{
if (func1) func1(4); else
printf("func1 not assigned\n");
}
void func(int num) { printf("num = %d\n", num); }
}
int main(char[][] args)
{
Foo a = new Foo;
a.dothis();
a.func1 = &a.func;
a.dothis();
return 0;
}
Result: func1 not assigned
num = 4
However, if I move the func declaration to outside of the class, the line "a.func1 = &func" produces the error message: toelem: cannot cast from void(*)(int num) to void delegate(int).
If I then change the t_func declaration from alias to typedef then I get: cannot implicitly convert void(*)(int num) to t_func.
If I go back to the original working code and change alias to typedef then I get: Internal error: e21r.c 78
What are the reasons for these error messages? It seems to me that all of these senarios should work.
Thanks,
Paul
| ||||
October 24, 2002 Re: Problems with delegates | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Paul Runde | Delegates are a combination of function pointer with a 'this' pointer. Hence, a function outside of a class can't be a delegate. I'll check into the internal error. Thanks, -Walter "Paul Runde" <prunde@mcleodusa.net> wrote in message news:3DB37363.30709@mcleodusa.net... > This code works: > > alias void delegate(int) t_func; > > class Foo > { > t_func func1; > > void dothis() > { > if (func1) func1(4); else > printf("func1 not assigned\n"); > } > > void func(int num) { printf("num = %d\n", num); } > } > > int main(char[][] args) > { > Foo a = new Foo; > a.dothis(); > a.func1 = &a.func; > a.dothis(); > return 0; > } > > Result: func1 not assigned > num = 4 > > However, if I move the func declaration to outside of the class, the > line "a.func1 = &func" produces the error message: toelem: cannot cast > from void(*)(int num) to void delegate(int). > If I then change the t_func declaration from alias to typedef then I > get: cannot implicitly convert void(*)(int num) to t_func. > If I go back to the original working code and change alias to typedef > then I get: Internal error: e21r.c 78 > > What are the reasons for these error messages? It seems to me that all of these senarios should work. > > Thanks, > > Paul > | |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply