Possible to convert list of #defines into strings (C++)
- by brandonC
Suppose I have a list of #defines in a header file for an external library. These #defines represent error codes returned from functions. I want to write a conversion function that can take as an input an error code and return as an output a string literal representing the actual #define name.
As an example, if I have
#define NO_ERROR 0
#define ONE_KIND_OF_ERROR 1
#define ANOTHER_KIND_OF_ERROR 2
I would like a function to be able to called like
int errorCode = doSomeLibraryFunction();
if (errorCode)
writeToLog(convertToString(errorCode));
And have convertToString() be able to auto-convert that error code without being a giant switch-case looking like
const char* convertToString(int errorCode)
{
switch (errorCode)
{
case NO_ERROR:
return "NO_ERROR";
case ONE_KIND_OF_ERROR:
return "ONE_KIND_OF_ERROR";
...
...
...
I have a feeling that if this is possible, it would be possible using templates and metaprogramming, but that would only work the error codes were actually a type and not a bunch of processor macros.
Thanks