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.
Overload
I recently discover “Overload” - a publication done bi-monthly by the ACCU (Association of C & C++ Users). It’s focus is on C++ and software engineering in general. The overall quality of the articles is quite good and they also have some well known names like Kevlin Henney or Peter Sommerlad writing articles for them. In my opinion a worthy alternative to the dearly missed “C/C++ User Journal”. The complete archive can be found here. Highly recommended!