The reason is mostly brevity. First of all, enum can be anonymous:
class foo { enum { bar = 1 }; };
This effectively introduces bar as an integral constant. Note that the above is shorter than static const int .
Also, no one could write &bar if he is a member of enum . If you do this:
class foo { static const int bar = 1; }
and then your class client does this:
printf("%p", &foo::bar);
then it will get the linker-time-linker error that foo::bar is undefined (because, well, like lvalue, itβs not). In practice, with the standard that currently stands, somewhere bar used where an integral constant expression is not required (i.e. where it is just allowed), it requires a definition outside the class foo::bar. such an expression is necessary: enum initializers, case labels, the size of the array in types (except for new[] ), and template arguments for integral types. Thus, the use of bar elsewhere technically requires determination. See C ++ Core Language Active Issue 712 for more details - no offers yet.
In practice, most compilers these days are more lenient to this and will allow you to avoid most of the "sound reasoning" of using static const int variables without requiring a definition. Nevertheless, angular cases may vary, but many believe that it is better to use an anonymous enum , for which everything is extremely clear, and there is no ambiguity at all.
Pavel Minaev Sep 04 '09 at 8:09 2009-09-04 08:09
source share