Defining type coercion
Jonathan M Davis
jmdavisProg at gmx.com
Sun Feb 27 22:10:59 PST 2011
On Sunday 27 February 2011 21:57:26 Simen kjaeraas wrote:
> Peter Lundgren <lundgrpb at rose-hulman.edu> wrote:
> > I'd like to define a type Ordinal which behaves like an int (using a
> > struct or
> > alias) that represents the 26 letters, A-Z, with the numbers 1-26. Then,
> > I
> > would like to be able to coerce between chars and Ordinals appropriately.
> >
> > chars and ints already have the ability to coerce between each other
> > using the
> > appropriate ASCII values. So, really, I'd just like to define a type that
> > overrides this behavior.
> >
> > As far as I can tell, the place to define such rules is with opCast!,
> > but I'm
> > at a loss for how to add additional rules to built in types.
>
> The D Programming Language (the book by Andrei) mentions that multiple
> alias this be a possibility. Sadly, it has not yet found its way its way
> into the actual implementation of the language.
>
> With it, one would define what you ask for, approximately like this:
>
> struct Ordinal {
> private int representation;
> char getChar( ) {
> return representation + 'a'-1;
> }
> alias representation this;
> alias getChar this;
> }
>
> But like I said, it currently does not work.
Would "alias getChar this" really be legal? I thought that this had to be
aliased to a type.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list