静态和动态模板初始化可以交错吗?

Can static and dynamic template initialization be interleaved?

据我了解,给定以下代码:

template<int N> 
int i = i<N - 1> + i<N - 1>;  // primary variable template

template<> int i<0> = 1;      // and explicit specialization

下面的程序必须return2:

int main () { return i<1>; }

但是这个程序可以 return 0 或 4:

int main () { return i<2>; }

因为评估 i<2> 的实例化给出:

int i<2> = i<1> + i<1>;       // generated by the compiler

这里,由于i<1>只是隐式实例化,编译器既可以使用i<1>的静态初始化值,即0,也可以使用动态初始化值,即0 2.

这里 comparison 不同的编译器给出不同的输出(clang returns 0,gcc returns 4)。

问题是——这个程序可以return2吗?

int main () { return i<2>; }

即在i<2>的初始化中,是否可以针对i<1>的不同用途进行不同的初始化?程序可以 return 完全是其他值吗?

the statically initialized value of i<1>, which is 0

你从哪里得到 0?您自己在该声明的上方说过 i<1> 必须是 2.

所以,给定:
i<0> = 1
并且:
i<1> = i<0> + i<0> = 1 + 1 = 2
并且:
i<2> = i<1> + i<1>
那么:
i<2> = 2 + 2 = 4

只能是 4。

您从 得知 i<1>i<2> 的动态初始化顺序不确定。不确定顺序的评估不能交错(重叠):

Evaluations A and B are indeterminately sequenced when either A is sequenced before B or B is sequenced before A, but it is unspecified which. [ Note: Indeterminately sequenced evaluations cannot overlap, but either could be executed first.  — end note ]

所以在int i<2> = i<1> + i<1>;的动态初始化中,两个被加数使用i<1>的静态值或动态值,取决于i<1>的动态初始化是否已经发生了。