Doubt about type Inference on templates

Paul Backus snarwin at gmail.com
Wed Nov 22 19:37:58 UTC 2023


On Wednesday, 22 November 2023 at 17:53:15 UTC, Antonio wrote:
> Basically, it doesn't know witch version of ```filter``` to 
> use, because it is inferring `i=>i%2==0` is `void` ?!?!?!
>
> ```
> !()(IIterable!int, void)
> ```
>
> If I explicitly write `(int i)=>i%2==0`, it compiles correctly 
> again.
>
> **Is it mandatory to explicitly tell that `S` is `int` when 
> ```IIterable!S source``` is  `IIterable!int` alredy?**

This is a bug/limitation in the compiler. I couldn't find an 
existing report on issues.dlang.org, so I've reported it myself 
as [issue 24255][1].

For now, I think the best way to work around it is to specify the 
type in the lambda, as in `(int i) => i%2 == 0`.

The reason you see `void` is that when the compiler cannot figure 
out the type of a function literal, it treats it as a template 
function:

```d
static assert(__traits(isTemplate, i => i % 2 == 0));
```

And for silly historical reasons, when the compiler tries to 
determine the type of a template, it returns `void` instead of 
giving an error:

```d
template example() {}
static assert(is(typeof(example) == void)); // what??
```

[1]: https://issues.dlang.org/show_bug.cgi?id=24255


More information about the Digitalmars-d-learn mailing list