Elegant human readable enums
While reading the source of some FOSS project i noticed that the authors have come up with a nice way to get human readable enums through the use of the “stringification feature” of the C/C++ preprocessor. The trick is that the members of the enum are declared through a macro which can be expanded in different ways.
-
#include <iostream>
-
#include <cstdlib>
-
#include <cassert>
-
#include <time.h>
-
-
namespace MyStuff
-
{
-
enum Things {
-
#define THING(X) X,
-
#include "things.def"
-
MAX_THINGS
-
};
-
-
static const char* const ThingNames[] = {
-
#define THING(X) #X,
-
// ^ preprocessor stringification
-
#include "things.def"
-
NULL
-
};
-
-
const char *toString(Things t) {
-
assert(t >= 0 && t < MAX_THINGS);
-
return ThingNames[t];
-
}
-
}
-
-
int main(int argc, char **argv)
-
{
-
using namespace MyStuff;
-
std::srand(::time(NULL));
-
for (int i = 0; i < 4; ++i) {
-
Things aRandomThing =
-
static_cast<Things>(std::rand() % MAX_THINGS);
-
}
-
}
-
things.def:
-
-
#ifndef THING
-
#define THING
-
#endif
-
-
THING(CELLPHONE)
-
THING(NOTEBOOK)
-
THING(CUP_OF_TEA)
-
THING(MOUSE)
-
-
#undef THING
-
Time after time i am amazed what you can do with some of the advanced preprocessor features like “token pasting” or stringification.
0 Comments