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