【发布时间】:2020-10-01 06:58:55
【问题描述】:
constexpr 函数的标准在 [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
【问题讨论】:
-
这是由 chat discussion 引发的。我想其他人可以加入该聊天。
-
模板也有类似的规则,模板应该具有可实例化的潜在类型/参数(禁止
static_assert(false);)。
标签: c++ language-lawyer constexpr constexpr-function