Enumeration Enumeration?

Let's say I create an enumeration, but in the end someone wants to add elements to this enumeration, what does it do? eg:

// blah.hpp enum PizzaDressing { DRESSING_OLIVES = 0, DRESSING_CHEESE = 1 }; 

and in my FunkyPizza class there may be toppings of pepper.

So how can I add pepper without explicitly changing the original listing?

Thank you

+11
source share
4 answers

Since enums are usually processed as some int size in the compiler, all you have to do is do it later

 enum PizzaDressing { Olives = 0, Cheese = 1, Pepperoni = 2 }; 

or you can let him count

 enum PizzaDressing { Olives = 0, Cheese = 1, Pepperoni }; 

You can, if for some reason this is not acceptable, use math ( Cheese + 1 ). You can play with the listing in almost any way using a numerical value.

Please note that the enumerator that you use is usually baked into the code by the compiler, it does not appear as its name, just a value. Thus, modification (extension) of the enumerator later will not lead to the creation of the code that was created.

I think this is legal syntax for using an enumeration in another enumerator with the application, but I have never tried. This might work, but kind of ugly:

 enum PizzaDressing { Olives = 0, Cheese = 1 }; enum OtherPizzaDressings { Start = (OtherPizzaDressings)PizzaDressing::Cheese; Pepperoni }; 
+4
source

This is closest to what you want: Inheriting the base enum class

+6
source

This will be known as dynamic enumeration. As far as I know, nothing like this exists in C ++. However, since we use C ++, not C, you can do something like this:

 #include <string> #include <map> std::map<std::string, int> myMap; myMap["DRESSING_OLIVES"] = 0; myMap["DRESSING_CHEESE"] = 1; myMap["PEPPER_TOPPING"] = 2; 
+2
source

You cannot dynamically change an enumeration because it only defines the new type allowed at compile time. They are mnemonics for the programmer, when compiled they are translated to numbers.

However, you can use any number not used by the original enumeration to represent what you want:

 PizzaDressing a; a = (PizzaDressing)5; 
0
source

Source: https://habr.com/ru/post/886032/


All Articles