4

Alot templated code looks like this:

template <typename T>
class foo
{
   enum { value = <some expr with T> };
};

An example can be seen here in the prime check program and I've seen it in a Factorial implementation once too.

My question is why use a nameless enum? Is there a particular reason to this? A static const int could work as well for example?

edit:

@Benoît: Thanks for the link, it provided the insight I was looking for!

2 Answers2

8

A static const variable would take up memory (like Sean said), whereas enums do not take any memory. They only exist in the compiler's world. At runtime they are just regular integers.

Other than that it would work, except for bad implementation of the standard by the compiler.

There is a thorough thread on the subject in boost mailing-list :

Benoît
  • 16,798
  • 8
  • 46
  • 66
  • @underscore_d can you give me any example that can explore how enum and const different in size? – Asif Mushtaq Dec 20 '15 at 07:45
  • I'd said `const[expr]` members would increase `sizeof(Obj)`, specifically meaning `static` ones, but in retrospect, I think I'm an idiot. I _should_ have said '`static const[expr]` variables will probably be allocated space in the executable image and possibly RAM', but not per-instance - for a very obvious reason: they're static. Now I'm away to test whether trivial `static const[expr]` constants are value-inlined by the compiler like `enum`s are. – underscore_d Dec 20 '15 at 10:51
  • any constant that can potentially have a pointer, will have to be in memory. const int x; for example would need to be in memory due to the possibility of someone doing const int * y = &x; Or const int& y = x; Or passing that constant by reference to a function fun(const int& x_); fun(x); etc. Meanwhile enums are constants that cannot be accessed by pointer or reference thus exist only at compile time. – rxantos Apr 25 '22 at 15:43
3

If I remember correctly, a static const would require you to allocate space by declaring and defining the variable whereas an unnamed enum doesn't.

Sean
  • 60,939
  • 11
  • 97
  • 136