Question

I have been moving code from my project to a static library. Most recently, I moved a command system to the static library, but left the events, because they were project specific. However, one of the events I use in the command constructor as a default. What I ended up doing was defining this event with the constructor and then allowing the original project to redefine this command and define the rest of the events.

Static Library:*

namespace Event
{
    enum Type
    {
        None = 0
    };
}

Command::Command()
: fcn()
, event(Event::None)
{
}

Original Project:

namespace Event
{
    enum Type
    {
        None    = 0,
        Enemey  = 1 << 0,
        Player  = 1 << 1,
    }
}

Is intentionally redefining the enum in this way a poor design choice?

Was it helpful?

Solution

That is illegal in C++, as it violates the One Definition Rule (ODR). For example, the compiler may choose a sensible width in bytes for the enum based on its contents. If one declaration has only one value and it is 0, and the other has many values which may be large, then you will end up with two different (incompatible) notions of how wide this enum type is. That's not going to work, and is a violation of the language requirements.

You might consider having the library take a plain integer of some kind (e.g. uint32_t or uint64_t), using 0 as the default, and just letting the enum values be opaque to the library (they must be anyway, since the library has no knowledge of any values other than zero).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top