I am writing part of a larger C++ program.
I want to write a header file, say, "Component.h", with code like this...
class Component{
private:
int value;
ComponentType component_type;
vector<Component> components_this_component_derives_from;
...
...
protected:
inline void setValue(int value) { this->value = value; }
inline int getValue() { return value; }
inline ComponentType getComponentType() { return component_type; }
inline void setComponentType(ComponentType component_type) { this->component_type = component_type; }
public:
Component() { value = 0; }
~Component() {}
void setupDependentComponents(vector<Component> dependentComponents){
components_this_component_derives_from = dependentComponents;
}
virtual void setupParams(vector<string> ¶ms) = 0;
virtual void init() = 0; // This is where setComponentType() is called
virtual bool isValid() = 0; // This is where dependent component types are checked and polymorphic behaviour of the component set up
virtual void calculate(customDataType custom_data) = 0;
}
All "Components" required will inherit this as a parent class. Some components require a certain type of components to derive from, or behave differently depending on the type of components it is set to derive from. For example, I expect ComponentA to depend on one component. If it depends on Component B of ComponentType::TypeX, it will multiply this value by 2 and call setValue() with this. However if Component B is of ComponentType::TypeY, it will square this value and call setValue() with this.
I have achieved this much by writing the following...
enum class ComponentType{
TypeX, TypeY, TypeZ
};
However now I need to divide each component type into subtypes. Something like...
enum class ComponentType{
enum class{
SubTypeA, SubTypeB
}TypeX,
enum class{
SubTypeA, SubTypeC, SubTypeD
}TypeY,
TypeZ
};
I want to use if/switch statements on the Type itself, as well as the SubType, if needed, so I am not sure namespaces would work.
The kind of code I want to write with if statements would be like this...
if(ComponentP.getComponentType != ComponentType::TypeX){
cerr << "Unexpected component type" << endl;
abort();
}
if(ComponentP.getComponentType == ComponentType::TypeX::SubTypeA){
...
} else {
...
}
How do I do this?
Edit: Just writing a namespace in place of the outer enum is not useful because not all component types have a subtype, and also because I cannot write something like if(ComponentA.getComponentType() == ComponentType::TypeA) { ... } if TypeA is just a namespace.
vector<Component>indicates you are doingusing namespace std;in header file (so worst possible case).class, anenum classis not a class! Had the committee dared to add a new keyword for this, it could have beenscoped enuminstead. Now they "cheated" and reused an existing keyword, even though its is quite confusing.inline; you don't have to mark itinline.