I would like to convert a vector of strings, e.g.
std::vector<std::string> fruit = {"Apple", "Banana", "Orange"};
into an enum class, as follows:
enum class fruitID : uint32_t {
Apple = 0;
Banana = 1;
Orange = 2;
_size
};
I'd appreciate any pointers to solve this, as I couldn't really find a good way of doing this looking through different answers. Thanks!
CodePudding user response:
As pointed out by the comments already there is no way to do this in C natively. You would have to generate source files dynamically in order to solve your problem.
The closest you can probably get is using a map as proxy. You can dynamically create it from your vector of strings and it is easy to use within the code, however, no compile-time checking for any range of valid values.
std::vector<std::string> fruit = {"Apple", "Banana", "Orange"};
int i = 0;
std::map<std::string, int> fruitID;
for (const auto& f : fruit)
{
fruitID[f] = i ;
}
Then use fruitID["Apple"]
etc. to use your "dynamic enum" in the code.