Const struct assign error messages

Jonathan M Davis jmdavisProg at gmx.com
Fri Mar 4 15:42:37 PST 2011


On Friday, March 04, 2011 15:19:22 bearophile wrote:
> This is a little wrong D2 program:
> 
> 
> void bar(const int data) {
>     auto d = data;
>     d = data;
> }
> void main() {}
> 
> 
> With the error message DMD gives it's easy to understand the error and fix
> it: test.d(3): Error: variable test.bar.d cannot modify const
> 
> 
> This is a similar program that uses a Tuple instead of an int:
> 
> import std.typecons;
> alias Tuple!(int) Foo;
> void bar(const Foo data) {
>     auto d = data;
>     d = data;
> }
> void main() {}
> 
> 
> But now the errors given are not so easy to understand:
> test.d(5): Error: template std.typecons.Tuple!(int).Tuple.opAssign(R) if
> (isTuple!(R)) does not match any function template declaration test.d(5):
> Error: template std.typecons.Tuple!(int).Tuple.opAssign(R) if
> (isTuple!(R)) cannot deduce template function from argument types
> !()(const(Tuple!(int)))
> 
> 
> Being that "d" a const Foo struct, that you can never be assigned to, can't
> DMD give a nicer error message, like in the first program?

Well, you just added a template into the mix. That complicates things 
considerably. It's going to have to actually instantiate the templated opAssign 
before it will have code to compare similar to the first situation. And since the 
template constraint is failing, the template doesn't get instantiated and so you 
don't get the nice error. I don't think that there's anything that the compiler 
can really do about that. If you adjusted the template constraint, you'd likely 
just get an error in compiling opAssign and that error would be in std.typecons, 
not your code, so it would make it lookng like std.typecons was broken rather 
than your code, and it would probably be much harder to track down, since I 
don't think that it would tell you which line of your code is causing the 
problem.

So, while I can see while you'd want a better error message, I don't think that 
you can do it with templated function. The way templates work just doesn't lend 
itself to doing what you want. You'd have to be able to instantiate an invalid 
template, which you obviously can't do.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list