I am writing a class for generating bitmask from a table of predefined element strings:
const std::unordered_map<std::string, int> flagMap
{ { "bananas", 0x1 }, { "apples", 0x2 }, { "oranges", 0x4 }, { "pears", 0x8 }};
int fruitMask(std::string & fruitName)
{
if(flagMap.count(fruitName) > 0)
return flagMap.at(fruitName);
else
return 0;
}
int fruitMask(const char * fruitName)
{
if(flagMap.count(fruitName) > 0)
return flagMap.at(fruitName);
else
return 0;
}
int fruitMask(std::vector<std::string> fruitNames)
{
int result = 0;
for(auto it=fruitNames.begin(); it!=fruitNames.end(); ++it)
{
if(flagMap.count(*it) > 0)
result = result | flagMap.at(*it);
}
return result;
}
int fruitMask(std::initializer_list<const char*> fruitNames)
{
int result = 0;
for(auto it=fruitNames.begin(); it!=fruitNames.end(); ++it)
{
if(flagMap.count(*it) > 0)
result = result | flagMap.at(*it);
}
return result;
}
When the code using these functions call the const char*
or the std::initializer_list<const char*>
versions of fruitMask
, is there any way to make it work at compile time?
For instance:
constexpr int mask = flagMask({"oranges", "bananas"});
This will not compile because flagMask() is not constexpr, is there any way to make this work? This would require a constexpr unordered_map, I do not even know if this is possible.