Multiple alias this failed workaround...obscure error message
via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jun 11 14:06:45 PDT 2014
On Wednesday, 11 June 2014 at 18:07:44 UTC, matovitch wrote:
> source/app.d(5): Error: basic type expected, not cast
> source/app.d(5): Error: no identifier for declarator int
> source/app.d(5): Error: semicolon expected to close alias
> declaration
> source/app.d(5): Error: Declaration expected, not 'cast'
> Error: DMD compile run failed with exit code 1
This particular error stems from the fact that you can only
define `alias this` to a symbol, but you are using a cast, which
is an expression. For this, a helper function is required:
class A(Derived) {
auto castHelper() {
return (cast(Derived) this).x;
}
}
(Note that you also need to remove the `ref` inside the cast,
because classes are already reference types, and the `ref` would
mean a reference to a reference.)
But this still doesn't work, as then the compiler crashes while
it tries to do the cast, iff the alias this is there. This works:
import std.stdio;
class A(Derived)
{
auto castHelper() {
return (cast(Derived) this).x;
}
//alias castHelper this;
}
class B : A!B
{
float x;
}
class C : A!C
{
int x;
}
void main()
{
auto b = new B;
b.x = 0.5;
auto c = new C;
c.x = 42;
float f = b.castHelper;
writeln("b = ", f);
int i = c.castHelper;
writeln("c = ", i);
}
But if you enable the `alias this` line, it segfaults. You don't
even need to reduce the calls to `castHelper` in the main
function, it evidently doesn't get that far.
More information about the Digitalmars-d-learn
mailing list