The reason is mainly brevity. First of all, an enum
can be anonymous:
class foo {
enum { bar = 1 };
};
This effectively introduces foo
as an integral constant. Note that the above is shorter than static const int
.
Also, no-one could possibly write &foo
if it's an enum
member. If you do this:
class foo {
static const int bar = 1;
}
and then the client of your class does this:
printf("%p", &foo::bar);
then he will get a compile-time linker error that foo::bar
is not defined (because, well, as an lvalue, it's not). In practice, with the Standard as it currently stands, anywhere bar
is used where an integral constant expression is not required (i.e. where it is merely allowed), it requires an out-of-class definition of foo::bar.
The places where such an expression is required are: enum
initializers, case
labels, array size in types (excepting new[]
), and template arguments of integral types. Thus, using bar
anywhere else technically requires a definition. See C++ Core Language Active Issue 712 for more info - there are no proposed resolutions as of yet.
In practice, most compilers these days are more lenient about this, and will let you get away with most "common sense" uses of static const int
variables without requiring a definition. However, the corner cases may differ, however, so many consider it to be better to just use anonymous enum
, for which everything is crystal clear, and there's no ambiguity at all.