Manipulating variables without evaluating them

ag0aep6g anonymous at example.com
Mon May 8 05:23:01 UTC 2023


On 07.05.23 19:11, Dadoum wrote:
> To overcome that, I create a template `plistDict` as such:
> 
> ```d
> template plistDict(alias U) {
>      PlistDict pl() {
>          auto dict = new PlistDict();
>          static foreach (elem; dict) {
>              dict[elem.key] = elem.value;
>          }
>          return dict;
>      }
> }
> ```

1. The `static foreach` can't work. `dict` is a run-time value. You 
can't iterate it at compile time like that.
2. `U` is unused.
3. You're just assigning everything from `dict` back to `dict`.

Did you maybe mean `static foreach (elem; U)`?

> The `static foreach` ensures everything is running at compile time, and 
> so no hash should mess with the keys. But the problem here is that it 
> tries to evaluate at compile time the value of each entry in the 
> associative array (what it can't do since it's a wrapper around a C 
> library!).

Hard to tell what's going on because your code is missing crucial parts: 
what is `PlistDict` and how are you instantiating `plistDict`?

> The same kind of issue can be encountered in this small code snippet:
> 
> ```d
> string crashingFunction() {
>      assert(!__ctfe);
>      return "OK";
> }
> 
> template macroLikeTemplate(alias U) {
>      string macroLikeTemplate() {
>          return "" ~ U;
>      }
> }
> 
> void main()
> {
>      macroLikeTemplate!(crashingFunction());
> }
> 
> ```

This one is a simple fix. Just don't call `crashingFunction` at the 
instantiation site:

     macroLikeTemplate!(crashingFunction);


More information about the Digitalmars-d mailing list