array of functions/delegates

MoonlightSentinel moonlightsentinel at disroot.org
Tue Dec 24 13:31:37 UTC 2019


On Tuesday, 24 December 2019 at 13:13:12 UTC, MoonlightSentinel 
wrote:
> On Tuesday, 24 December 2019 at 10:40:16 UTC, Mike Parker wrote:
>> struct S {}
>> void f1(S s) {}
>> void f2(S s) {}
>>
>> alias Func = immutable(void function());
>>
>> immutable Func[2] funcs = [cast(Func)&f1, cast(Func)&f2];
>>
>> Though, it's not clear to me wy the one requires casting the 
>> pointer type and the other doesn't.
>
> Because typeof(&f1) == void function(S)

Working example without casts using type deduction:

import std.stdio: writeln;

struct S {}
void f1(S s) { writeln("f1"); }
void f2(S s) { writeln("f2"); }

immutable funcs = [&f1, &f2];

void main() {
     S s;
     foreach(f; funcs) {
     	f(s);
     }
}


More information about the Digitalmars-d-learn mailing list