The most confusing error message

Meta jared771 at gmail.com
Wed Jan 24 14:22:59 UTC 2018


On Wednesday, 24 January 2018 at 07:21:09 UTC, Shachar Shemesh 
wrote:
> test.d(6): Error: struct test.A(int var = 3) is used as a type
>
> Of course it is. That's how structs are used.
>
> Program causing this:
> struct A(int var = 3) {
>     int a;
> }
>
> void main() {
>     A a;
> }
>
> To resolve, you need to change A into A!(). For some reason I 
> have not been able to fathom, default template parameters on 
> structs don't work like they do on functions.

IMO the error message is not too bad once you understand what's 
going on (which probably means it's really not a good error 
message).

struct A(int var = 3) is short for:

template A(int var = 3)
{
     struct A
     {
         //...
     }
}

As I'm sure you know.

If it's written out like this then I think it makes it obvious 
what the problem is. When you write `A a`, you're trying to use 
this template like a type, but templates are not types; they are 
used to _construct_ types. Therefore, to construct a valid type 
from the template A, you have to instantiate it by declaring an 
`A!() a`.

The compiler could allow implicit insatntiation if the template 
has 0 arguments or only default arguments, but as Jonathan 
showed, this causes a lot of ambiguous cases that are better 
avoided.

One way we could probably improve the error message is to change 
it to "template struct test.A(int var = 3) is used as a type. It 
must be instantiated", or something along those lines, to make it 
clear why you can't use A as a type.


More information about the Digitalmars-d mailing list