Defining type coercion

Bekenn leaveme at alone.com
Sun Feb 27 16:20:22 PST 2011


On 2/27/2011 12:10 PM, Peter Lundgren 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.

I haven't tried anything like this yet (I'm still pretty new to D), but 
I think something like this is the best you'll be able to do:

struct Ordinal
{
	this(int value) { m_Value = value; }
	this(dchar ch) { m_Value = ch - 'a' + 1; }	// add range checks as 
appropriate

	alias this m_Value;
	T opCast(T)() if (T is dchar) { return m_Value + 'a' - 1; }

	// add more operators as appropriate

private:
	int m_Value;
}


More information about the Digitalmars-d-learn mailing list