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

constexpr qualifier added on a non constexpr function does not trigger any warning

似乎编译器在将 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 个州

For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression (8.20), or, for a constructor, a constant initializer for some object (6.6.2), the program is ill-formed, no diagnostic required.

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