该标准关于常量表达式函数[decl.constexpr] 第 5 点规定:
对于非模板、非默认 constexpr 函数或非模板、非默认、非继承 constexpr 构造函数,如果不存在参数值,则函数或构造函数的调用可以是核心常量的计算子表达式表达式(5.19),程序格式错误;无需诊断。
为此,它继续给出以下示例:
constexpr int f(bool b){ return b ? throw 0 : 0; } // OK
constexpr int f() { return f(true); } // ill-formed, no diagnostic required
我从中得出的结论是,具有空参数列表的函数是无法诊断的格式错误的函数。这让我印象深刻极其奇怪,以至于我怀疑我的理解是错误的。例如,这是否也是格式错误的:
constexpr int g() { return 0; } // ill-formed?
如果是这样,其背后的基本原理是什么?如果不是,限定意味着什么/ constexpr 函数何时会变得格式错误?
大概下面这些都可以吧?
constexpr int h(int x) { return x; } // presumably fine?
constexpr int l = h(42); // also fine
该规则的基本原理是应该最后一个可以在其中评估函数的上下文constexpr
语境。例如给定:
constexpr int f(bool b){ return b ? throw 0 : 0; } // OK
constexpr int f() { return f(true); } // ill-formed, no diagnostic required
没有办法调用f()
in a constexpr
上下文,因为all通过此函数的路径将以不是核心常量表达式.
编译器必须评估all可能的调用来查看该函数是否可以在constexpr
语境。一般来说,这不容易诊断,所以语言说它是格式错误,无需诊断,即你做错了什么,但编译器无法诊断它。
请注意,如果零参数重载f
如下:
constexpr int f() { return f(false); } // ok
那很好,因为评估以核心常量表达式.
同样,这个函数:
constexpr int g() { return 0; } // ok
还有这个:
constexpr int h(int x) { return x; } // ok
constexpr int l = h(42); // ok
都很好,因为g
and h
可以在一个中调用constexpr
语境。
的措辞“...如果不存在参数值使得...”可能会令人困惑,因为您已经询问了g
. But g
可以用零参数调用,或者换句话说,用void
争论,所以没关系。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)