array of functions/delegates

Steven Schveighoffer schveiguy at gmail.com
Thu Dec 26 17:43:19 UTC 2019


On 12/24/19 8:52 AM, MoonlightSentinel wrote:
> 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?
> 
> You can set funcs within the constructor but not as a default 
> initializer because they have to be compile time constants 
> (https://dlang.org/spec/struct.html#default_struct_init)
> 
> struct S
> {
>      void f1() {}
>      void f2() {}
> 
>      alias Func = void delegate();
> 
>      immutable Func[2] funcs;
> 
>      this(bool)
>      {
>          funcs = [&f1, &f2];
>      }
> }
> 
> &f1 creates a delegate which contain a function pointer and the context 
> pointer (struct, closure, ...). In this example the latter contains a 
> pointer to a concrete instance of S which is a usually a runtime value. 
> (https://dlang.org/spec/type.html#delegates)

Just FYI, doing this is very suspicious. Storing a delegate to a struct 
means you have a context pointer to that struct. And structs can usually 
move around freely. Meaning that f1 and f2 are still going to refer to 
the original struct, even if it has been copied, and even if the struct 
has been deallocated (i.e. it was on a stack frame that no longer exists).

-Steve


More information about the Digitalmars-d-learn mailing list