Make enum auto castable

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 4 18:42:55 PDT 2017


On Monday, June 05, 2017 01:30:47 Mike B Johnson via Digitalmars-d-learn 
wrote:
> enum X : EnumX
> {
>     a = 1,
> }
>
>
> struct EnumX
> {
>   int x;
>   alias x this;
>   void opAssign(int y)
>   {
>       x = y;
>   }
>   double opCall()
>   {
>              return x;
>   }
> }
>
> doesn't work because "1" is not castable to EnumX, even though
> EnumX is aliased to an int, and hence it should work fine.
>
> Seems like a bug to me.

It's not a bug. The alias this conversion only goes one way. It provides a
way to convert _from_ the type that it's declared on to another type, not
from the other type to the type that it's declared on. There is no way in D
to declare an implicit conversion in the direction you're trying. So, if you
have a struct that wraps an int like this, and you want to assign it an int,
you're going to need to explicitly construct the struct - e.g. EnumX(1).

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list