Alex Rivera | Logout

Template Metaprogramming - Difference Between Using Enum Hack and Static Const

Asked 2010-01-31T17:47:53.977
62

I'm wondering what the difference is between using a static const and an enum hack when using template metaprogramming techniques.

EX: (Fibonacci via TMP)

template< int n > struct TMPFib {
  static const int val =
    TMPFib< n-1 >::val + TMPFib< n-2 >::val;
};

template<> struct TMPFib< 1 > {
  static const int val = 1;
};

template<> struct TMPFib< 0 > {
  static const int val = 0;
};

vs.

template< int n > struct TMPFib {
  enum {
    val = TMPFib< n-1 >::val + TMPFib< n-2 >::val
  };
};

template<> struct TMPFib< 1 > {
  enum { val = 1 };
};

template<> struct TMPFib< 0 > {
  enum { val = 0 };
};

Why use one over the other? I've read that the enum hack was used before static const was supported inside classes, but why use it now?

Edit
Report

1 Answer

12

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.

answered 2010-01-31T17:54:29.260

Your Answer