jmasterx
jmasterx

Reputation: 54103

Extending an enum?

Say I create an enum but eventually someone wants to add items to that enum, what does one do? ex:

// blah.hpp

enum PizzaDressing {
    DRESSING_OLIVES = 0,
    DRESSING_CHEESE = 1
};

and in my FunkyPizza class, there might be pepper toppings.

So how could I add peppers without obviously modifying the original enum?

Thanks.

Upvotes: 13

Views: 27413

Answers (4)

rubenvb
rubenvb

Reputation: 76519

This is closest to what you want: Base enum class inheritance

Upvotes: 8

Andrew Rasmussen
Andrew Rasmussen

Reputation: 15099

That would be known as a "dynamic enum". To the best of my knowledge, nothing like this exists in C++. However, since we're using C++ and not C, you could 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;

Upvotes: 5

lvella
lvella

Reputation: 13413

You can't dynamically modify an enum, because it only defines a new type resolved at compile time. They are mnemonics for the programmer, at compilation they are translated to numbers.

That said, you can use any number not used by the original enum to represent whatever you want:

PizzaDressing a;
a = (PizzaDressing)5;

Upvotes: 1

ssube
ssube

Reputation: 48247

Since enums are typically handled as some size of int in the compiler, all you have to do is later make

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

or you could allow it to count

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

You could, if neither of those is acceptable for some reason, use math (Cheese + 1). You can play around with the enum in almost any way you could with a numeric value.

Note that the enumerator you use is typically baked into the code by the compiler, it doesn't show up as its name, simply value. Thus, modifying (extending) the enumerator later on will not effect code that has been built.

I think it's legal syntax to use an enumeration in another enumerator, with casts, but I've never tried it. This may work, but is kind of ugly:

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

enum OtherPizzaDressings
{
    Start = (OtherPizzaDressings)PizzaDressing::Cheese;
    Pepperoni
};

Upvotes: 5

Related Questions