为什么用g ++编译该代码会花费这么长时间?

Rus*_*lan 11 c++ gcc templates compilation

考虑以下代码:

template<int i> class A
{
    typedef A<i-1> B;
    B x, y;
};
template<> class A<0> { char m; };
int main()
{
    A<LEVEL> a;
}

Run Code Online (Sandbox Code Playgroud)

通过以下Bash命令(使用g ++ 8.3.0)对g ++编译进行基准测试时

template<int i> class A
{
    typedef A<i-1> B;
    B x, y;
};
template<> class A<0> { char m; };
int main()
{
    A<LEVEL> a;
}

Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

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
Run Code Online (Sandbox Code Playgroud)

因此,编译时间在中是指数的LEVEL。但是,如果我更改B x, y;B x[2];,则编译将在固定时间内(约30毫秒)进行。

为什么会发生?我以为,因为编译器知道Band是一个相同的类型,所以它xycompile花费的时间相同x[2]。但是由于某种原因,它似乎有所不同。我能以某种方式强制B实现(而不是简单地使用别名),以便g ++可以像创建数组一样容易地创建两个变量吗?

Hey*_*yji 1

因为你的 g++ 实例中有一个错误。它不应该,正如 @Marc Glisse 评论的那样,你应该报告它(在撰写本文时你已经这样做了)

那么您可能想删除您的问题。