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

c – 在常量表达式上下文中定义之前嵌套的`constexpr`函数调用

发布时间:2020-12-16 06:52:00 所属栏目:百科 来源:网络整理
导读:根据我从 this answer收集的内容,如果函数尚未声明,则constexpr函数的结果不是常量表达式.令我惊讶的是以下代码片段: constexpr int f();constexpr int g() { return f();}constexpr int f() { return 42;}int main() { constexpr int i = g(); return i;}
根据我从 this answer收集的内容,如果函数尚未声明,则constexpr函数的结果不是常量表达式.令我惊讶的是以下代码片段:

constexpr int f();

constexpr int g() {
    return f();
}

constexpr int f() {
    return 42;
}

int main() {
    constexpr int i = g();
    return i;
}

这编译没有麻烦和工作.移动f的定义超过主触发器错误:’constexpr int f()’在其定义之前使用,正如我所料.

我认为它的工作原理是因为在调用g之前定义了f,因此两个调用都是常量表达式.

为什么f()和g()显然是常量表达式,即使f在被g调用时没有定义f?标准如何描述?

我在Coliru的GCC 6.1.0和Clang 3.8.0上测试了这个.

解决方法

在使用constexpr之前没有必要定义它.但是,在定义之前调用它的结果不是constexpr.因此,编译器正确地抱怨,因为您尝试使用非常量表达式初始化constexpr变量.

§5.20/ p2常量表达式[expr.const](强调我的):

A conditional-expression e is a core constant expression unless the
evaluation of e,following the rules of the abstract machine (1.9),
would evaluate one of the following expressions:

(2.3) — an invocation of an undefined constexpr function or an undefined constexpr constructor;

(编辑:李大同)

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

    推荐文章
      热点阅读