CPP Limit int type by max value
Saturday 31 December 2022

For the past couple of weeks I have been reviewing #CPP, and while doing so I’m creating a small Snake game

I started the game without any images at all. everything is a rectangle and then when the game was working I wanted to replace the food rectangle with an image that moves. and found an asset of itch.io with a spinning coin sprite.

The sprite is 5 frames each 16 pixels. so to draw one of these frames each drawing operation I had to store the current frame number and for every iteration I increase it and when it goes out of bound I reset it to zero;

1int frame = 0;
2frame = (frame+1) % 5;

That makes the frame include only the values (0,1,2,3,4). So I wanted to flex a bit and make a type that’s an Int that I can increment it and it bounds itself to a max value.

My first attempt was using a template.

 1template<int max>
 2class LimitedInt {
 3public:
 4  LimitedInt() : v {0}{};
 5  operator int() const { return v; };
 6  LimitedInt<max>& operator++(int) {
 7    v = (v+1) % max;
 8    return *this;
 9  };
10
11private:
12  int v;
13};

this can be used as follows:

1LimitedInt<5> frame;
2frame++;

the frame unary (++) operation will increase the int by 1 and reset it when it reaches 5. same behavior. I just can reuse the class multiple times when I need this behavior for another sprite.

But I thought for a while and figured that I don’t really need the template at all. I can get away by storing max in the class itself.

 1class LimitedInt {
 2public:
 3  LimitedInt(int max) : v {0}, max {max}{};
 4  operator int() const { return v; };
 5  LimitedInt& operator++(int) {
 6    v++;
 7    v %= max;
 8    return *this;
 9  };
10
11private:
12  int v;
13  int max;
14};

and it will be used as follows:

1LimitedInt frame(5);
2frame++;

And frame can be used as int as I overloaded the int operator (that’s my TIL).

Here is the final code as part of the snake game

Backlinks

See Also