My first question is about how to create a private static member variable which is an array of enums, and where the enum is also defined within the class. That is, I would *like* to write something like this:
But this code won't compile: When I try to initialize the array of enums, the enum type Colors is not accessible, presumably because it's private. The problem is really a general one of not being able to initialize a static array whose members are of a type defined privately within a class. Yet it seems there must be some way to do this.....
My second question is about the performance of using enums. Assume I running a simulation which performs thousands of comparisons in a loop. Will it be faster to compare ints or enums for equality? Or will it be the same?
Types declared private cannot be used by anyone other than the class that declared them.
You may be able to initialize TestStaticEnum::_colorsArray within the class definition. I know static const integers can be initialized this way, but I'm not sure about enums.
Note that line 7 neither declares an array, nor defines TestStaticEnum::_colorsArray.
My second question is about the performance of using enums.
Read this http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.19
On most compilers enums will be at least as fast as ints (at least if you don't force the compiler to use long integers by assigning some huge value to one of the enum values).
R0mai's solution works and the code below compiles fine.
Given that enums compile to ints, is there another way to improve performance when I know that I will only have 8 values or less (ie, all of values can be represented by 3 bits only). My thought is that to test equality of ints, all 32 bits would need to be compared when they happen to be equal, in order to prove equality. This would be waste since I know in advance that all of the bits after bit 3 are 0 for my data. Is there a way to take advantage of that knowledge?
is there another way to improve performance when I know that I will only have 8 values or less
No. Because:
1. The size of an enum is fixed. It can't be changed any more than the size of an int can be changed.
2. Comparing two integers smaller than a CPU register takes exactly as much time as comparing two integers as big as a CPU register, so that gets you nothing. If the enum variable is aligned in memory you wouldn't get an improvement when loading it to a register, either, because memory is accessed in words at a time. E.g. x86 reads 4 bytes at a time at addresses multiple of 4. x86-64 reads 8 bytes at a time at addresses multiple of 8. This doesn't mean that at other addresses these architectures read fewer bytes; it means that they can only read memory in this manner.
An int, signed or unsigned, is always the fastest possible type for all operations.