Mark P wrote:
> I'm working on a project where I have something like
>
> enum Modes {mode_a, mode_b, ...};
>
> Due to project spec changes, the number of Modes has increased several
> times. There are a few places where it's useful to know the number of
> image modes (to set the size of bitsets, etc.) Currently I just use a
> const int to hold this size:
>
> enum Modes {mode_a, mode_b, mode_c};
> const int number_of_modes = 3;
>
> I'm wondering what the style gurus think about this alternative:
>
> enum Modes {mode_a, mode_b, mode_c, mode_sentinel};
> const int number_of_modes = mode_sentinel;
>
> The second version requires just a bit less work to maintain, but is it
> trying to be too clever? FWIW, the numerical values of the enum
> elements are otherwise not used anywhere.
The only problem with that is that the sentinel is a valid enum, so
void SetMode( Modes );
void Foo()
{
SetMode( mode_sentinel ); // Ok, but probably won't work
}
Enums aren't perfect in any case [the compiler needn't complain about
"(Modes)0xfffff" either], but I prefer this style:
enum Modes
{
mode_min = 0,
mode_a = mode_min,
mode_b,
mode_c,
mode_max = mode_c
};
enum { n_modes = (mode_max - mode_min) + 1 };
void Bar()
{
SetMode( n_modes ); // Compile-time error
}
It also allows one to iterate relatively easily:
for( Modes m = mode_min; m <= mode_max; m = Modes(m+1) )
{
// ...
}
Cheers! --M
|