Template Metaprogramming - Difference Between Using Enum Hack and Static Const

Enums aren't lvals, static member values are and if passed by reference the template will be instanciated:

void f(const int&);
f(TMPFib<1>::value);

If you want to do pure compile time calculations etc. this is an undesired side-effect.

The main historic difference is that enums also work for compilers where in-class-initialization of member values is not supported, this should be fixed in most compilers now.
There may also be differences in compilation speed between enum and static consts.

There are some details in the boost coding guidelines and an older thread in the boost archives regarding the subject.


For some the former one may seem less of a hack, and more natural. Also it has memory allocated for itself if you use the class, so you can for example take the address of val.

The latter is better supported by some older compilers.


On the flip side to @Georg's answer, when a structure that contains a static const variable is defined in a specialized template, it needs to be declared in source so the linker can find it and actually give it an address to be referenced by. This may unnecessarily(depending on desired effects) cause inelegant code, especially if you're trying to create a header only library. You could solve it by converting the values to functions that return the value, which could open up the templates to run-time info as well.