C++ Enum hack (transfer)

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 GameTurnthe 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 hackThe trick used, the idea is to define GameTurnit 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 hackThe benefits described in Effective C++ :

  1. enum hackbehaves more like #definenot const, if you don't want others to get pointers or references to your const members, you can use that enum hackinstead. (Why not use it directly #define? First of all, because it #defineis a string replacement, it is not conducive to program debugging. Second, #definethe visible range #defineof #undef.

  2. Use enum hackdoes not cause "unnecessary memory allocations".

  3. enum hackis 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.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325827805&siteId=291194637