Any workaround for "closures are not yet supported in CTFE"?

Petar Petar
Wed Dec 8 21:52:22 UTC 2021


On Wednesday, 8 December 2021 at 12:17:42 UTC, Stanislav Blinov 
wrote:
> On Wednesday, 8 December 2021 at 08:07:59 UTC, Petar Kirov 
> [ZombineDev] wrote:
>
>> ```d
>> interface ICallable
>> {
>>     void opCall() const;
>> }
>>
>> alias Action = void delegate();
>>
>> struct A
>> {
>>     Action[] dg;
>> }
>> ```
>
> At this point why not just call a spade a spade and store an 
> array of ICallables directly? :) I mean, why store fat pointers 
> to fat pointers?

Initially that's exactly what I tried, and it worked if the 
result was stored as `static const` / `static immutable`, but it 
didn't when using the `enum`:


```
onlineapp.d(39): Error: variable `onlineapp.main.a` : Unable to 
initialize enum with class or pointer to struct. Use static const 
variable instead.
```

```d
interface ICallable
{
     void opCall() const;
}

auto makeDelegate(alias fun, Args...)(auto ref Args args)
{
     return new class(args) ICallable
     {
         Args m_args;
         this(Args p_args) { m_args = p_args; }
         void opCall() const { fun(m_args); }
     };
}

alias Action = void delegate();

ICallable createDelegate(string s)
{
     import std.stdio;
     return makeDelegate!((string str) => writeln(str))(s);
}

struct A
{
     ICallable[] dg;
}

A create()
{
     A a;
     a.dg ~= createDelegate("hello");
     a.dg ~= createDelegate("buy");
     return a;
}

void main()
{
     enum a = create();
     foreach(dg; a.dg)
         dg();
}
```


I didn't have time to fully investigate the issue and report this 
compiler limitation.


More information about the Digitalmars-d-learn mailing list