lundi 28 janvier 2019

Pattern to extend an enum in C++

I have a base class that defines some common states shared by all subclasses and subclasses may be able to add more specific states. As it is not possible to extend an enum in C++, i have this code :

class AbstractMachine
{
public:
    enum State {
        AbstractMachineState1,
        AbstractMachineState2,
        AbstractMachineState3
    };
    virtual enum State state() const = 0;
    // ..
};

class Machine : public AbstractMachine
{
public:
    // more specific states related to Machine
    enum MachineState {
        MachineState1,
        MachineState2,
        MachineState3
    };
    virtual enum State state() const = 0;
    virtual enum MachineState machineState() const = 0;
    // ..
};

class SpecificMachine : public Machine
{
public:
    // more specific states related to SpecificMachine
    enum SpecificMachineState {
        SpecificMachineState1,
        SpecificMachineState2,
        SpecificMachineState3
    };
    SpecificMachine();
    virtual enum State state() const;
    virtual enum MachineState machineState() const;
    virtual enum SpecificMachineState specificMachineState() const;
    // ..
};

The client code should be able to handle 3 levels of abstraction but then, to get the state of any SpecificMachine i need to call :

state()
machineState()
specificMachineState()

How is it possible to have the state of any SpecificMachine within one call to state() ?

Adding all states in the AbstractMachine enum would work but i don't like the idea to modify the base class every time we need to add a new SpecificMachine.

Thank you.

Aucun commentaire:

Enregistrer un commentaire