enums are first class types in c++...

Sep 10, 2007 13:24

I somehow had always thought that they were some kind of half-type (like arrays) that basically got rewritten into int as soon as possible by the compiler. However, apparently they are treated like real types -- at least by g++.
Check this code out.

#include enum M { A_VALUE, B_VALUE, }; template void log(const T&); template <> void log(const M& m) { switch(m) { case A_VALUE: printf("Got A\n"); break; case B_VALUE: printf("Got B\n"); break; default: printf("unknown\n"); break; } } template <> void log(const int& m) { printf("Wrong specialization\n"); } int main(void) { M m; m = A_VALUE; log(m); m = B_VALUE; log(m); m = (M)234; log(m); log(1234); log((M)1234); return 0; }
It's proof-of-concept code that partially specializes a templated log function to understand how to print enums "nicely". Crazy.
Previous post Next post
Up