You can't cast from char *
to enum
, they are incompatible types. You have three options
Use an
if (strcmp(textualRepresentation, "EnumValue1") == 0)
return EnumValue1;
else if (strcmp(textualRepresentation, "EnumValue2") == 0)
return EnumValue2;
Create a struct containing both the textual representation and the value of the enum
and then use bsearch()
to match the textual representation and retrieve the enum
value.
struct EnumData {
const char *name;
Enum value;
};
EnumData enums[ENUM_COUNT] = {
{"EnumValue1", EnumValue1},
{"EnumValue2", EnumValue2}
};
int compare_enums(const void *const lhs, const void *const rhs)
{
return strcmp(reinterpret_cast<const EnumData *>(lhs)->name,
reinterpret_cast<const EnumData *>(rhs)->name);
}
and then search like this
EnumData key;
void *found;
key.name = "EnumValue2";
found = bsearch(&key, enums, ENUM_COUNT, sizeof(EnumData), compare_enums);
if (found != NULL)
std::cout << reinterpret_cast<EnumData *>(found)->value << " is the enum value" << std::endl;
Use std::map<const char *,Enum>
, this is the best option.
The following code demonstrates the methods 2 and 3, method 1 is evident
enum Enum {
InvalidEnumValue,
EnumValue1,
EnumValue2,
EnumCount
};
struct EnumData {
const char *name;
Enum value;
};
static EnumData enums[EnumCount] = {
{"EnumValue1", EnumValue1},
{"EnumValue2", EnumValue2},
{"InvalidEnumValue", InvalidEnumValue}
};
int compare_enums(const void *const lhs, const void *const rhs)
{
return strcmp(reinterpret_cast<const EnumData *>(lhs)->name,
reinterpret_cast<const EnumData *>(rhs)->name);
}
Enum find_enum_value_with_bsearch(const char *const name)
{
EnumData key;
void *found;
key.name = name;
found = bsearch(&key, enums, EnumCount, sizeof(EnumData), compare_enums);
if (found == NULL)
return InvalidEnumValue;
return reinterpret_cast<EnumData *>(found)->value;
}
int
main()
{
Enum value;
std::map<const char *,Enum> enumsMap;
enumsMap["EnumValue1"] = EnumValue1;
enumsMap["EnumValue2"] = EnumValue2;
value = find_enum_value_with_bsearch("EnumValue2");
std::cerr << value << std::endl;
std::cerr << enumsMap["EnumValue1"] << std::endl;
}