Consider the following code:
template<int i> class A
{
typedef A<i-1> B;
B x, y;
};
template<> class A<0> { char m; };
int main()
{
A<LEVEL> a;
}
When benchmarking its compilation by g++ by the following Bash command (with 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
I get the following output:
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
So, compilation time is exponential in LEVEL
. But if I change B x, y;
to B x[2];
, then compilation happens in constant time (~30 ms).
Why does it happen? I thought that, since the compiler knows that B
is one and the same type for both x
and y
, it would take the same time as compiling x[2]
. But for some reason it appears different.
Can I somehow force B
to be realized (as opposed to simply aliased) so that g++ could create both variables just as easily as it created the array?
Header files Every single compilation unit requires hundreds or even thousands of headers to be (1) loaded and (2) compiled. Every one of them typically has to be recompiled for every compilation unit, because the preprocessor ensures that the result of compiling a header might vary between every compilation unit.
The -g option instructs the compiler to generate debugging information during compilation. In C++, the -g option turns on debugging and turns off inlining of functions. The- g0 (zero) option turns on debugging and does not affect inlining of functions.
g++ also has additional macros. So you can compile C code with g++ and in fact mix both C and C++ code.
Because there is a bug in your g++ instance. It should not, and as @Marc Glisse commented, you should report it (which you have done at the time of writing)
You might want to delete your question then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With