C++ 变量模板。这是UB?

标签 c++ templates c++14

我创建了一个简单的 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/

相关文章:

c++ - basic_string 文字在编译时速度更快还是处理得更好?

c++ - 模板函数指针作为模板参数

c++ - 什么是 c++11/14/17 等同于 ltoa/itoa 的 C 函数?

c++ - 在编译时检测 C++ 中的函数

c++ - 对 unordered_map 的奇怪行为感到震惊

c# - .net 电子邮件模板引擎

c++ - 构造函数中的模板类转换

c++ - 如何使用 Direct2D 创建自定义窗口镶边?

c++ - 如何中断QThread中运行的select/pselect

c++ - windows接收到中断的处理时间