我创建了一个简单的 C++14 变量模板来计算阶乘(仅供学习)。然后我想打印前 12 个阶乘。
template <int n> const int fact = n * fact<n - 1>;
template <> const int fact<0> = 1;
如果我替换 fact<12>
与 fact<i>
在下面的片段中,我得到一个错误,因为 i
不是常数。
int main()
{
for(int i = 0; i < 12; i++){
std::cout << fact<12> << std::endl;
}
}
但是当我把它改成这个时,我得到了预期的结果。
int main()
{
for(int i = 0; i < 12; i++){
std::cout << *(&fact<12> - i) << std::endl;
}
}
这是未定义的行为吗?它在 GCC 8.3 上按预期工作。 Live example here
最佳答案
是UB。您的指针运算“偶然发生”(使用 UB 任何事情都可能发生)。
你可能会这样做,例如:
template <std::size_t ... Is>
void print_fact(std::index_sequence<Is...>)
{
for (int res : {fact<Is>...}) {
std::cout << res << std::endl;
}
}
int main()
{
print_fact(std::make_index_sequence<12>());
}
关于C++ 变量模板。这是UB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56781981/