Reprinted from: http://www.cnblogs.com/jiqingwu/p/cpp_enum_hack.html
Let's start with an example:
class Game { private : static const int GameTurn = 10 ; int scores [GameTurn]; };
For C++ compilers that support in-class initialization, this code will compile fine.
But older C++ compilers may not support in-class initialization, so our static constants must be initialized outside the class. as follows:
class Game { private : static const int GameTurn; int scores [GameTurn]; }; const int Game :: GameTurn = 10 ;
If not int scores[GameTurn];
, this code can pass with a compiler that doesn't support in-class initialization.
But because it is int scores[GameTurn];
used GameTurn
, and GameTurn
the value of can not be determined. So the following error will be reported.
enum_hack.cpp:5: error: array bound is not an integer constant
In this case, if we still don't want to specify the size of the array with a hardcoded number, we can consider the protagonist enum hack
of this article: .
enum hack
The trick used, the idea is to define GameTurn
it as an enum constant. The above code can be written as:
class Game { private : // static const int GameTurn; enum {GameTurn = 10 }; int scores [GameTurn]; }; // const int Game::GameTurn = 10;
This code can be compiled and passed.
enum hack
The benefits described in Effective C++ :
-
enum hack
behaves more like#define
notconst
, if you don't want others to get pointers or references to your const members, you can use thatenum hack
instead. (Why not use it directly#define
? First of all, because it#define
is a string replacement, it is not conducive to program debugging. Second,#define
the visible range#define
of#undef
. -
Use
enum hack
does not cause "unnecessary memory allocations". -
enum hack
is a fundamental technique of template metaprogramming and is used by a lot of code. When you see it, you have to recognize it.
I don't know if my understanding is wrong, welcome to discuss.