I want to use C++ to create an enum
whose members have members.
I had a similar question here, but that one dealt with D, not C++.
In Python, I can do this:
class Product(enum.Enum):
PHOTOSHOP = "Image editor.", 0
FIREFOX = "Web browser.", 1
NOTEPAD = "Text editor.", 2
def __init__(self, description, num):
self.description = description
self.num = num
>>> print(Product.PHOTOSHOP.description)
>>> "Image editor."
Java can do something like this:
public enum Product {
PHOTOSHOP("Image editor.", 0),
FIREFOX("Web browser.", 1),
NOTEPAD("Text editor.", 2);
private final String description;
private final int num;
Product(String description, int num) {
this.description = description;
this.num = num;
}
}
Can I do this in C++?
If something to this effect can’t be done in C++, what’s a good alternative?
3
Answers
As far as I’m aware you can’t have multi-component enums in C++, though I don’t claim to be an expert.
What you can do however is declare an enum and use it to look up strings in an array.
By going to a struct rather than an enum, you can accomplish something similar:
Unfortunately you can’t use
std::string
, since it isn’t a “literal” type, and thus not eligible for use inconstexpr
objects.Another issue with this is that the type of the enumerands is
Product::type
, not justProduct
, and this will affect any code where you need to declare a variable. It’s just not possible to use inline definition and also have the same type for the items as the type that contains them.I realize it does not answer the question, but a full featured enum inevitably requires passing around a reference to a singleton instead of just a value (thus affecting spacial locality of the code). That would not be the C++ way.
The C++ way would be to only pay the price when you have to. For instance:
The above can be made compile time friendly with a few easy tweaks if needed.