Adding a method to an enum.
Ali Çehreli
acehreli at yahoo.com
Sun Jun 19 21:54:49 PDT 2011
On Mon, 20 Jun 2011 02:48:30 +0000, Charles McAnany wrote:
> Hi, all. I'm looking for a way to make constants that have methods
> without a lot of overhead. In particular, a way to define a Direction
> and then be able to rotate it right. Here's kind of what I have in mind:
>
> enum Direction{
> left, right, up, down;
>
> public Direction rotateRight(){
> switch(this){
> case left:
> return up;
> case up:
> return right;
> case right:
> return down;
> case down:
> return left;
> }
> }
It may be acceptable to change a Direction variable freely in a different
context. So I think that the requirement on how a Direction variable
change should not be on the Direction type itself.
How about a Dial that has a Direction:
struct Dial
{
Direction direction_;
void rotateRight(int count = 1)
{
direction_ += count;
direction_ %= Direction.sizeof;
}
void rotateLeft(int count = 1)
{
rotateRight(-count);
}
@property Direction direction() const
{
return direction_;
}
}
Ali
More information about the Digitalmars-d-learn
mailing list