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?
This isn't an array of functions you're creating here. A pointer
to a member function is *always* a delegate, unless the function
is static. Pointers to functions can be known at compile time, so
this works:
struct S () {
static void f1() {}
static void f2() {}
alias Func = void function();
immutable Func[2] funcs = [&f1, &f2];
}
As does this:
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.