I need to check if some values are defined in the enum type or not at runtime in C++. The requirement could be easily accomplished by C# (refer the following code). But C++ doesn’t have type information at runtime (as far as I know). Is there a way to workaround?
PS: In my project, the enum type defines hundreds of values, so I don’t want to duplicate the values in source code (e.g. create a map and push all the valid values into it) that implements the logic which increases the complexity of maintainability.
enum BoFormObjectEnum
{
fo_Items = 4,
fo_SalesEmployee = 53,
fo_TransactionTemplates = 55,
fo_JournalPosting = 30,
fo_CheckForPayment = 57,
fo_PaymentTermsTypes = 40,
...
}
class Program
{
static void Main(string[] args)
{
var array = Enumerable.Range(1, 60);
foreach (var item in array)
{
if (Enum.IsDefined(typeof(BoFormObjectEnum), item))
// do some logic
else
// do some other logic
}
}
}
C++ does not provide what you want.
Most “proper” solution is to re-design the whole thing, and not use C++ enum like this. It is not same as C# enum, they are different enough that you should not think of them as a same thing, any more than you think union and enum are same thing. Clear your mind of C# solution, design C++ solution.
Easiest, especially if enum values do not change often (and if they do, why are they a hard-coded enum?), is to just “bite the bullet” and create a set or a map with valid values, and when you want to know if some number is defined as enum, test if it is in set, or if you also want the name, then use map so you can include both value as int and name as string.