This code completely breaks the compiler:

Ruby The Roobster rubytheroobster at yandex.com
Fri Aug 19 13:31:46 UTC 2022


On Friday, 19 August 2022 at 05:50:17 UTC, Mike Parker wrote:
> On Friday, 19 August 2022 at 04:25:25 UTC, Ruby The Roobster 
> wrote:
>
>> [...]
>
> If the template is never instantiated, it never makes it into 
> the executable. It doesn't matter if it's in production or not, 
> and has nothing to do with tests. It doesn't exist. How could 
> the compiler catch any problems if it has no idea what `Mtypes` 
> is?
>
> This is true for any template parameter. Consider this:
>
> ```d
> import std.stdio;
>
> T derp(T)(T val) {
> 	val += 10;
>     return val;
> }
>
> void main()
> {
>     writeln("Hello D");
> }
> ```
>
> `derp` obviously isn't going to work with every type. But this 
> code compiles because `derp` is never instantiated. The 
> compiler can't check if the code in `derp` is valid because it 
> has no idea what `T` might be. If it's `int`, then no problem. 
> If it's `string` then no way:
>
> ```d
> void main()
> {
>     writeln(derp!string("No way"));
> }
> ```
>
> Now you'll get this:
>
> ```
> onlineapp.d(4): Error: slice `val` is not mutable
> onlineapp.d(10): Error: template instance 
> `onlineapp.derp!string` error instantiating
> ```

This makes sense.  Still, in my code, where the function has the 
same return type regardless of instantiation, the compiler should 
at least check that expressions independent of the template 
parameter are valid.


More information about the Digitalmars-d-learn mailing list