TheRiver | blog

You have reached the world's edge, none but devils play past here

0%

enum hack

参考

zhihu

case1 static

1
2
3
4
5
6
7
8
9
10
11
12
class Game {
private:
static const int GameTurn = 9; //ok
int scores[GameTurn]; //ok
};

//const int Game::GameTurn = 10;

int main()
{

}

这样是ok的,但有些老的编译期可能不允许在声明的时候给static变量赋值,就得做变通:

1
2
3
4
5
6
7
8
9
10
11
12
class Game {
private:
static const int GameTurn; //ok
int scores[GameTurn]; //not ok
};

const int Game::GameTurn = 10;

int main()
{

}

如此这般scores的数组大小就取不到了。形如case2

case2 const

1
2
3
4
5
6
7
8
9
10
11
12
class Game {
private:
const int GameTurn = 10; //ok
int scores[GameTurn]; //not ok
};

//const int Game::GameTurn = 10;

int main()
{

}

由于类没有实例化,这里数组大小还是取不到,不像static是在类外实例化的。

case3 enum

1
2
3
4
5
6
7
8
9
10
11
12
class Game {
private:
enum hack {GameTurn = 10};
int scores[GameTurn];
};

//const int Game::GameTurn = 10;

int main()
{

}

如此这般可行,甚好。enum是在编译期求值得,可用于模板元编程,见下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

template <unsigned long long data>
struct test{
enum {
result = data + test<data - 1>::result
};
};

template<>
struct test<1>
{
enum {
result = 1
};
};

int main()
{
const unsigned long long num = 10;
std::cout << test<num>::result << std::endl;
}

ending

----------- ending -----------