Issue with casting types

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 17 05:48:28 PDT 2016


On 05/17/2016 02:24 PM, Thorsten Sommer wrote:
> Dear all,
>
> I run into an issue with a simple cast:
> https://dpaste.dzfl.pl/8e7f7c545eb1
>
> I have a base class and a class A with inherit from that base class:
> A <- BaseClass
>
> If the base class contains an "alias this", any casting attempt fails
> because the "alias this" type gets considered. Thus, I defined the
> opCast() to solve this. But now, the program crashes without any error
> or exception...

You've got an infinite recursion there.

`A a2 = to!A(b1);` calls `b1.opCast!A()` which calls `to!A(this)` which 
is the very same call as `to!A(b1)`, so it calls `opCast!A()` again, and 
so on until the stack is exhausted and the program crashes.

> Why does the casting operation consider the "alias this" at all? I mean:
> The "alias this" type is int. If I try to cast with to!A, obviously int
> does not match A!?

There's an issue on this: https://issues.dlang.org/show_bug.cgi?id=6777

I don't know if there's a good reason for the current behavior. Looks 
silly to me.

> Is there any practical solution? Or should I stop using "alias this" for
> my classes? I like the "alias this" concept. But it caused some issue
> for me...

You can use the reinterpreting style of cast to circumvent features like 
alias this and opCast:
----
A a2 = * cast(A*) &b1;
----


More information about the Digitalmars-d-learn mailing list