Is there a way to reverse #define instruction?
In the following example
#define ZERO 0
#define ONE 1
#define TWO 2
#define THREE 3
is it possible to retrieve TWO from the integer value 2?
This example comes from a C code but I can use some C++ code if needed. My goal is to be able to factorize some spurious switch-case loops of this form :
switch(num)
{
case ZERO:
return std::to_string(foo.V_ZERO);
case ONE:
return std::to_string(foo.V_ONE);
case TWO:
return std::to_string(foo.V_TWO);
case THREE:
return std::to_string(foo.V_THREE);
}
where foo is an instance of a structure like this:
struct Foo
{
union Val
{
int V_ZERO;
int V_ONE;
double V_TWO; // nonsense: just to say that types are not the same
int V_THREE;
};
};
My constraints are the following:
- I can't remove the functionality provided by #define, i.e. I can write something equivalent, e.g. an enumeration, but I can't lose the map between ZERO and 0, ONE and 1 etc;
- the existing code is written in C and I can't rewrite it in C++. However, I can write some supplementary C++ code.
I have some ideas to simplify the code but I wonder if there is a very known elegant way of doing this, especially by means of some templates or preprocessor directives.
EDIT: usage of std::to_string added to say that I am not interested in knowing how to convert or handle multiple types from a union.