在常量表达式上下文中定义之前嵌套`constexpr`函数调用 [英] Nested `constexpr` function calls before definition in a constant-expression context

查看:532
本文介绍了在常量表达式上下文中定义之前嵌套`constexpr`函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我从此回答收集到的资料, 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



我假定它的工作原因是 f 已经在调用 c 和 g()显然是常量表达式,即使 f $ c> g ?



我已经在Coliru的GCC 6.1.0和Clang 3.8.0上测试过了。

解决方案

由TC链接在他的评论,则必须遵守缺陷报告



< blockquote>

根据5.20 [expr.const]项目符号2.3,表达式是一个常量
表达式,除非(除其他原因)它将评估




  • 调用未定义的 constexpr 函数或未定义的 constexpr 构造函数;



这并不解决 constexpr
函数必须定义。为了允许
相互递归 constexpr 函数,意图是函数必须在最外层评估之前定义
,最终导致
调用,但这没有明确说明。


这说明示例格式良好,确实按照预期工作,只要 f 在调用 g 之前定义。


From what I gather from this answer, a constexpr function's result is not a constant-expression if the function has not been declared yet. What surprises me is the following code snippet :

constexpr int f();

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

constexpr int f() {
    return 42;
}

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

This compiles without trouble and works. Moving f's definition past main triggers error: 'constexpr int f()' used before its definition, as I would expect.

I presume that it works because f has been defined before the call to g, thus both calls are constant expressions.

Why are f() and g() apparently constant-expressions, even though f isn't defined when it is called by g? How is this described by the Standard?

I have tested this on Coliru's GCC 6.1.0 and Clang 3.8.0.

解决方案

As linked by T.C. in his comment, this is subject to a defect report.

According to 5.20 [expr.const] bullet 2.3, an expression is a constant expression unless (among other reasons) it would evaluate

  • an invocation of an undefined constexpr function or an undefined constexpr constructor;

This does not address the question of the point at which a constexpr function must be defined. The intent, in order to allow mutually-recursive constexpr functions, was that the function must be defined prior to the outermost evaluation that eventually results in the invocation, but this is not clearly stated.

This makes it clear that the example is well-formed and should indeed work as expected as long as f is defined before the call to g.

这篇关于在常量表达式上下文中定义之前嵌套`constexpr`函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆