Thursday, July 19, 2007

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 {

enum Operation2 {

does not compile, because the two ERROR constants collide.
The same goes for a enum constant and a namespace:

namespace Plugin {
    enum Id {
    // ...
    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*

No comments:

Post a Comment