On 28/02/2016 22:06, Stefan Ram wrote:
> Victor Bazarov <v.ba...@comcast.invalid> writes:
>> As your compiler suggests, define your own operator:
>> Direction& operator++(Direction& d) {
>> switch (d) {
>> case NORTH: d = EAST; break;
>> case EAST: d = SOUTH; break;
>> case SOUTH: d = WEST; break;
>> case WEST: d = NORTH;
>> }
>> return d;
>> }
> Yes. But, /if/ the numerical values are appropriate,
> then one might also:
>
> #include <iostream>
> #include <ostream>
>
> enum direction { NORTH, EAST, SOUTH, WEST, TOP };
>
> direction operator+( const direction d, int const n )
> { return static_cast< direction >
> ( ( static_cast< int >( d )+ n )% static_cast< int >( TOP ) ); }
>
> int main()
> { direction x( NORTH );
> for( int i = 0; i < 9; ++i )::std::cout <<( x = x + 1 )<< '\n'; }
>
> 1
> 2
> 3
> 0
> 1
> 2
> 3
> 0
> 1
>
Not sure how safe this approach is and is it recommended? I mean, what
if somebody changes EAST to say, 5 later on?
In any case, I think with this approach there should be heavy comments
near direction to warn about this, that not to change the integer values.