加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 可能的模板和constexpr – 如果不兼容

发布时间:2020-12-16 05:33:57 所属栏目:百科 来源:网络整理
导读:我想在编译时计算e值(不用担心,不是作业),但出了点问题. templatesize_t limit = 3,class result = std::ratio0,1,size_t factorial = 1,size_t count = 1constexpr double e_impl() { if constexpr(limit == 0) { return static_castdouble(result{}.num) /
我想在编译时计算e值(不用担心,不是作业),但出了点问题.
template<size_t limit = 3,class result = std::ratio<0,1>,size_t factorial = 1,size_t count = 1>
constexpr double e_impl() {
    if constexpr(limit == 0) {
        return static_cast<double>(result{}.num) / result{}.den;
    }
    return e_impl<limit - 1,std::ratio_add<result,std::ratio<1,factorial>>,factorial * count,count + 1>();
}

虽然计算值是正确的,但编译器会抛出有关模板溢出的错误.似乎限制变量超出范围(低于0),但它不应该发生,因为0-case由if constexpr(…)语句处理.

所以问题是,我错了,应该预期这种行为,还是编译错误?用GCC 7.1.0编译.

解决方法

要避免错误,请将第二个返回显式放入else分支:
template<size_t limit = 3,size_t count = 1>
constexpr double e_impl() {
    if constexpr(limit == 0) {
        return static_cast<double>(result{}.num) / result{}.den;
    }
    else
    {
      return e_impl<limit - 1,count + 1>();
    }
}

https://godbolt.org/g/PdV7m7

合理的:

During an instantiation of the enclosing function template or generic lambda,if the converted condition is true and the statement includes a constexpr else substatement,that substatement is not instantiated.

http://open-std.org/JTC1/SC22/WG21/docs/papers/2016/p0128r1.html

它没有说明一个无约束的else块,或一个不应该运行的块,因此它被实例化,抛出错误. (注意:铿锵声也失败了)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读