Transferred from: http://www.cnblogs.com/jiqingwu/p/cpp_enum_hack.html
Let's start with an example:
class Game {private: staticconstintten; int Scores[gameturn];};
For C + + compilers that support in-class initialization, this code can be compiled through.
However, older C + + compilers may not support in-class initialization, so that our static constants must be initialized outside of the class. As follows:
class Game {private: staticconstint gameturn; int Scores[gameturn];}; Const int ten;
If not int scores[GameTurn];
, this code can be passed with a compiler that does not support in-class initialization.
But int scores[GameTurn];
GameTurn
GameTurn
The value cannot be determined because it is used. Therefore, the following error is reported.
enum_hack.cpp:5: error: array bound is not an integer constant
In this case, if we still do not want to specify the size of the array with hard-coded numbers, you can consider the main character of this article: Yes enum hack
.
enum hack
the idea of using the technique is to GameTurn
define a constant as an enumeration. The above code can be written as:
class Game {private: // static const int Gameturn; enum Ten }; int Scores[gameturn];}; // const int game::gameturn = ten;
This will allow the code to be compiled and passed.
The benefits described in effective C + + enum hack
:
enum hack
The behavior is more like #define
, rather than const
, if you don't want others to get pointers or references to your constant members, you can use enum hack
them instead. (Why not use #define
it directly?) First, because #define
it is a string substitution, it is not conducive to program debugging. Second, #define
the visual range is difficult to control, such as how do you make #define
the defined constants visible only within a class? Unless you're using an ugly #undef
.
Use does enum hack
not result in "unnecessary memory allocation".
enum hack
is a basic technique of template meta-programming, and a lot of code is using it. When you see it, you need to know it.
I do not know whether my understanding is wrong, welcome to discuss.
C + + enum hack (ext.)