【问题标题】:constexpr qualifier added on a non constexpr function does not trigger any warning在非 constexpr 函数上添加的 constexpr 限定符不会触发任何警告
【发布时间】:2018-08-01 14:22:37
【问题描述】:

似乎编译器在将 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;
}

【问题讨论】:

  • 它只适用于某些编译器。最好检查一下标准对此的规定。
  • @AndreySemenov 我不知道为什么,我在我的机器上成功编译。我正在使用 cmake 完成所有工作并将其设置为 c++ 11。这可能是个问题?

标签: c++ function c++11 constexpr


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多