请考虑以下代码:
template<int i> class A
{
typedef A<i-1> B;
B x, y;
};
template<> class A<0> { char m; };
int main()
{
A<LEVEL> a;
}
使用以下 Bash 命令(使用 g++ 8.3.0)来对其编译进行基准测试:
for ((level=1; level<30; ++level)); do
echo -n ${level},
/usr/bin/time -f %U g++ -DLEVEL=$level test.cpp -o /dev/null
done
我得到以下输出:
1,0.03
2,0.03
3,0.04
4,0.04
5,0.04
6,0.04
7,0.04
8,0.04
9,0.03
10,0.04
11,0.02
12,0.04
13,0.02
14,0.03
15,0.04
16,0.05
17,0.05
18,0.08
19,0.11
20,0.20
21,0.35
22,0.67
23,1.30
24,2.52
25,5.02
26,10.23
27,19.96
28,40.30
29,80.99
因此,编译时间是指数级的LEVEL
。但是如果我将B x, y;
更改为B x[2];
,那么编译时间会在常数时间内完成(约为30毫秒)。
为什么会这样呢?我以为,由于编译器知道B
是x
和y
的相同类型,它将花费与编译x[2]
相同的时间。但出于某种原因似乎不同。
我能否以某种方式强制实现B
(而不仅仅是创建别名),以便g ++可以像创建数组一样轻松地创建两个变量?