opImplicitCast/opImplicitCastFrom

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu Oct 30 09:24:00 PDT 2008


bearophile wrote:
> A possible Pascal-inspired syntax to specify the bounds of all integral values:
> 
> typedef int : 1 .. 7 TyDice1; // int in [1, 6]
> typedef ubyte : 1 .. 7 TyDice2; // ubyte in [1, 6]
> typedef ubyte : 1 .. 300 TyWarriors; // compilation error
> int : 1 .. 1000 i; // int in [0, 999]
> ubyte ub; // the same as  ubyte : 0 .. 256 ub;
> char : 'a' .. 'z'+1 c; // char in [a, z]
> 
> Possibile alternative syntax:
> 
> typedef int TyDice1 : 1 .. 7; // int in [1, 6]
> typedef ubyte TyDice2 : 1 .. 7; // ubyte in [1, 6]
> typedef ubyte TyWarriors : 1 .. 300; // compilation error
> int i : 1 .. 1000; // int in [0, 999]
> ubyte ub; // the same as  ubyte ub : 0 .. 256;
> char c: 'a' .. 'z'+1; // char in [a, z]

Why worry about syntax? The use of typedefs makes syntax even less 
relevant in the examples above, as users would emply the typedef'ed 
names, not the nice interval notations.

I'm thinking maybe we should start with library types. The nice thing 
about those is that they allow you to specify infinite behavioral 
variations via policies. For example, you'd want to choose the behavior 
on overflow to be e.g. throwing, unchecked, or wraparound:

typedef Bounded!(int, 1, 7, OnOverflow.nocheck) TyDice1;
typedef Bounded!(char, 'a', 'z', OnOverflow.throwing) TyLowercaseAscii;
...

I do agree that syntax may constitute an acceptance threshold, i.e. 
users may be willing to use a particular feature only if it also comes 
packaged with an easy-enough syntax.

> Plus some syntax to locally enable/disable the bound checks (-release disables them globally):
> 
> unsafe(integral, bounds) {
>     // here both array bounds and integral bounds aren't checked
>     ...
> }

That would be more interesting because it can't be done conveniently via 
a library.


Andrei




More information about the Digitalmars-d mailing list