|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
The ProblemC++ does not have a facility to allow one enum type to be extended by inheritance as it does for classes and structures. Sometimes it is important to have this functionality. Suppose you had: // in Fruit.h enum Fruit { Orange, Mango, Banana }; // in eat.h #include "Fruit.h" void eat(Fruit fruit); If you wanted to add another fruit type, you could extend Fruit as follows: enum Fruit { Orange, Mango, Banana, Apple, Pear };
You could also have another function that handles the extra fruit: void consume(Fruit fruit);
There are two problems with this approach:
In summary, the results of calls to eat( Orange ); // compiles and behaves as expected consume( Orange ); // compiles and behaves as expected eat( Apple ); // compiles with UNDEFINED BEHAVIOUR consume( Apple ); // compiles and behaves as expected
The Solution
Following on from our example, to handle new fruits as well as the first set of fruits, we will then have: // in -- MyFruit.h -- #include "Fruit.h" #include "InheritEnum.h" enum NewFruits { Apple, Pear }; typedef InheritEnum< NewFruit, Fruit > MyFruit; Now our void consume(MyFruit myfruit);
Now, our call summary looks as follows: eat( Orange ); // compiles and behaves as expected consume( Orange ); // compiles and behaves as expected eat( Apple ); // does not compile as eat() does not handle NewFruit consume( Apple ); // compiles and behaves as expected
The Code// -- InheritEnum.h template <typename EnumT, typename BaseEnumT> class InheritEnum { public: InheritEnum() {} InheritEnum(EnumT e) : enum_(e) {} InheritEnum(BaseEnumT e) : baseEnum_(e) {} explicit InheritEnum( int val ) : enum_(static_cast<EnumT>(val)) {} operator EnumT() const { return enum_; } private: // Note - the value is declared as a union mainly for as a debugging aid. If // the union is undesired and you have other methods of debugging, change it // to either of EnumT and do a cast for the constructor that accepts BaseEnumT. union { EnumT enum_; BaseEnumT baseEnum_; }; };
Thank you.
|
||||||||||||||||||||||