On Friday, 4 April 2014 at 04:31:41 UTC, Walter Bright wrote:
On 4/3/2014 7:19 PM, bearophile wrote:
I have asked for fully typesafe enums in D,


You can do this:

   struct MyInt {
       int x;
       alias this x;
       ... put your various constraints here ...
   }

to get typesafe enums. In fact, you can use this construct to create a type that overrides selected behaviors of any other type.

Combined with your other post about casts, I'm not sure we're talking about the same kind of type-safety. In the case of your example, alias this does not make it typesafe, as a MyInt can still be implicitly converted to int.

struct MyInt
{
        int x;
        alias x this;
}

void takesInt(int n)
{
}

void main()
{
        //Fine
        takesInt(MyInt(1));     
}


Implicit conversions are generally not a facet of type-safe systems. Saying that too-strong typing is bad because casts break the type system is a strawman, although I agree that there is a balance that must be struck.

Reply via email to