Manipulating variables without evaluating them
ag0aep6g
anonymous at example.com
Mon May 8 12:01:35 UTC 2023
On Monday, 8 May 2023 at 11:42:44 UTC, Dadoum wrote:
> ```d
> auto plistDict(alias AA)()
> {
> auto dict = new string[AA.length];
> foreach (key, value; AA)
> {
> dict[key] = value;
> }
> return dict;
> }
>
> import std.stdio;
>
> extern(C) void functionThatCannotBeEvaluatedAtCompileTime();
>
> string conversionFunction(string val) {
> functionThatCannotBeEvaluatedAtCompileTime();
> return val;
> }
>
> void main()
> {
> auto plist = plistDict!([
> 0: "zero".conversionFunction, // Error:
> `functionThatCannotBeEvaluatedAtCompileTime` cannot be
> interpreted at compile time, because it has no available source
> code
> 1: "one".conversionFunction,
> 2: "two".conversionFunction,
> ]);
> plist.writeln;
> }
> ```
[...]
> Is there a way to use the associative array here at compile
> time while avoiding the evaluation of those keys?
Instead of passing values, pass functions that return the values:
```d
auto plist = plistDict!([
0: () => "zero".conversionFunction,
1: () => "one".conversionFunction,
2: () => "two".conversionFunction,
]);
```
And in `plistDict`, call the functions:
```d
static foreach (key, fun; AA)
{
dict[key] = fun();
}
```
More information about the Digitalmars-d
mailing list