array of functions/delegates

Alex sascha.orlov at gmail.com
Tue Dec 24 09:10:42 UTC 2019


On Tuesday, 24 December 2019 at 07:37:02 UTC, Rumbu wrote:
> I am trying to create an array of functions inside a struct.
>
> struct S {
>   void f1() {}
>   void f2() {}
>
>   alias Func = void function();
>
>  immutable Func[2] = [&f1, &f2]
>
> }
>
> What I got: Error: non-constant expression '&f1'
>
> Tried also with delegates (since I am in a struct context but I 
> got: no `this` to create delegate `f1`.
>
> So, is there any way to have an array of functions without 
> adding them at runtime?

If you don't need runtime, probably like this:

´´´
import std;

void f1(S s) {assert(1);}
void f2(S s) {assert(1);}
alias field = AliasSeq!(f1, f2);

struct S{}

void main()
{
     S s;
     field[0](s);
}
´´´

Don't know why UCFS doesn't work in this case though.

Maybe, this is also helpful:
https://forum.dlang.org/post/mailman.2415.1354291433.5162.digitalmars-d-learn@puremagic.com


More information about the Digitalmars-d-learn mailing list