static const values are treated as r-values just like enum in 99% of code you'll see. That means there is never memory generated for them. The only advantage to using enums is they can't become l-values in that other 1%. The static const
value has the advantage that it is type safe. You can also have static const float
values.
The compiler will make Foo::Life
an l-value if it has memory associated with it. The primary way to do that is to take it's address. e.g. &Foo::Life;
Using gcc there is another more subtle way!
int foo = rand()? Foo::Life: Foo::Everthing;
The compiler generated code uses the addresses of Life and Everthing. It compiles fine but will give a linker error about the missing addresses for Foo::Life
and Foo::Everthing
. This behavior is completely standard conforming, though obviously undesirable.
Note, neither of these statements will generate the linker error.
int foo = rand()? Foo::Life: Bar::Life;
int bar = rand()? Foo::Life: Foo::Everthing + 0;
Once you have a compiler conforming to the C++0x the correct code will be
class Foo
{
public:
constexpr size_t Life = 42;
};
This is guaranteed to always be an l-value, the best of both worlds.