July 2007 Archives
2007-07-20
a class is not a namespace
Because the scope operator makes no difference between classes and namespaces people tend to think, that classes are like namespaces. But this is not true, as
- classes can not nest further namespaces, only further classes
- classes can not be imported by a using decleration
- classes can not be reopenend
- classes have access rights
One of the consequences is, that the "nest the enum into a namespace in order to import all constants"-trick and the "replace all enums by namespaces with constant integers"-workaround from my previous post do not work, if the enum is defined inside a class.
2007-07-19
enum's C legacy
Enums are annoying.
- they can not be extended, e.g. by inheritance
- they can not be enriched with construtors and cast operators
- they do not introduce a new namespace
The last point is the most annoying one for me. The defined constants are embedded in the namespace which surrounds the enum. So, for instance
enum Operation1 {
//...
ERROR
};
enum Operation2 {
//..
ERROR
};
does not compile, because the two ERROR constants collide.
The same goes for a enum constant and a namespace:
namespace Plugin {
enum Id {
SomePlugin
};
// ...
namespace SomePlugin {
// implementation of SomePlugin
}
}
and similar constelations.
Another consequence is, that it is not possible to import all constants of an enum with one using statement. Instead you need somethine like this
namespace MyEnum {
enum MyEnum {
// constants...
};
}
to be able to import the constants with a single using MyEnum.
Replacing a enum by a namespace with constants has some disadvantages:
- You need to enumerate the constants on your own.
- A enum function parameter must be replaced by a const int, and one can not contrain the legal values on constants from the namespace.
- You loose the convenient compiler warnings on enums, for instance if you forget a possiblity in a switch statement without a default case.
So, nothing helps. Enums are a C heritage, so no wonder that it sucks. But you nevertheless need them. *shrug*