Created attachment 1059
Example of bad + good error
When attempting to use 'this' in a static member function on a struct, the
error message is not helpful.
bad_error_static_this_struct.d(13): Error: need 'this' to access member x
However if the same declaration is made to be 'class' the error is much more
appropriate:
bad_error_static_this_struct.d(25): Error: 'this' is only defined in non-static
member functions, not comparex
Attached is an example.
Comment #1 by clugdbug — 2011-12-29T10:02:03Z
The class error message is generated in the front-end. The struct error message is generated in the glue layer. Apart from the diagnostic issue, the error should really be generated in the front-end.
Having it in the glue layer creates problems for CTFE. The following example errors with "variable x is used before initialization" which is nonsense.
struct BadError
{
double x = 2.0;
static int comparex()
{
return (this.x <= 3.0);
}
}
static assert({ BadError z; z.comparex(); return true; }());
Comment #2 by andrej.mitrovich — 2014-04-28T12:13:20Z
Unfortunately both examples now emit the less informative diagnostic:
-----
struct S
{
int x;
static void f() { x = 1; }
}
class C
{
int x;
static void f() { x = 1; }
}
void main() { }
-----
test.d(4): Error: need 'this' for 'x' of type 'int'
test.d(10): Error: need 'this' for 'x' of type 'int'
Comment #3 by robert.schadek — 2024-12-13T17:57:29Z