Compile-time global mutables
bauss
jj_1337 at live.dk
Thu Jun 30 12:55:43 UTC 2022
On Thursday, 30 June 2022 at 12:26:54 UTC, HuskyNator wrote:
> I've found several instances in which incrementation during
> compile time is required.
> One example is generation of unique ID's (although there might
> be some workarounds), another interesting idea the registration
> of a function's call-count to some image loader;
>> Anyone know of a way in c++ to track static resource usage at
>> compile time, basically i am trying to find a way so an
>> routine can just do Image("foobar.jpeg2000"), at an arbitrary
>> point in operation and I'll make sure the resources are
>> resident before the Job gets run.
>
> Although this references c++, I have attempted to make this
> work in D. It seems there are no workarounds that would make
> this work sadly. (I've even tried writing to files instead but
> this is not possible during ctfe)
>
> Essentially speaking, there are numerous instances in which
> generating a list or incrementing a value is useful during
> compile-time. I find this should be possible.
>
> One main argument against this seems to be the
> non-deterministic nature of this, though this is not an issue
> in virtually all cases in which doing this is useful or
> necessary I find. Essentially speaking when order does not
> matter and membership is only required during run-time.
>
> Are there other limiting factors preventing this possibility?
> It would allow for some powerful things that currently seem
> impossible to implement (save for some case-specific
> workarounds).
You can already do that.
```d
enum counter(size_t x = [__traits(allMembers,
mixin(__MODULE__))].length)=x;
char[] member(ulong x)
{
char[] buf = "void[0] _X0000000000000000;".dup;
enum mapping = "0123456789abcdef";
foreach_reverse(i; buf.length-17 .. buf.length-1)
{
buf[i] = mapping[x & 0xf];
x >>= 4;
}
return buf;
}
mixin template increment()
{
mixin(member(counter!()));
}
pragma(msg, counter!());
mixin increment;
pragma(msg, counter!());
mixin increment;
pragma(msg, counter!());
```
Credits: p0nce
More information about the Digitalmars-d
mailing list