在非constexpr函数上添加的constexpr限定符不会触发任何警告



似乎编译器在将constexpr限定符添加到非constexpr函数时忽略了它。为什么?

以下代码编译良好并运行。

#include <iostream>
#include <string>
using std::string; using std::cout; using std::endl;
constexpr bool is_shorter(const string &lft, const string &rht) // this is not a constexpr function
{
return lft.size() < rht.size();
}
int main()
{
bool restul =  is_shorter("Hello", "World!");
return 0;
}

发生这种情况的原因是标准允许它这样做。[dcl.constexpr]/5表示

对于既不是默认值也不是模板的constexpr函数或constexpr构造函数,如果不存在参数值,从而调用该函数或构造函数可以是核心常量表达式的求值子表达式(8.20(,或者对于构造函数,可以是某个对象的常量初始值设定项(6.6.2(,则程序格式错误,无需诊断。

因此,由于函数永远不可能是核心常量表达式,因此行为是未定义的,编译器不需要通知您。

相关内容

最新更新