This code completely breaks the compiler:
Mike Parker
aldacron at gmail.com
Fri Aug 19 05:50:17 UTC 2022
On Friday, 19 August 2022 at 04:25:25 UTC, Ruby The Roobster
wrote:
> So that's why it compiled. Still, I believe that stuff like
> this ought to be detected at compile time, as supposed to in a
> unittest or, if someone forgot to write the tests, in
> production.
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
```
More information about the Digitalmars-d-learn
mailing list