【问题标题】:Non-literal within a constexpr function (via std::is_constant_evaluated)constexpr 函数中的非文字(通过 std::is_constant_evaluate)
【发布时间】:2020-11-02 12:47:52
【问题描述】:

constexpr 函数中,我无法在受C++20 的std::is_constant_evaluated() 条件的if 语句的分支内定义非文字变量? Clang 和 GCC 都表示不允许,但在下面的示例中,允许在编译时无法评估的其他构造。对非字面量的使用有具体限制吗?

#include <type_traits>

struct Foo {
  ~Foo() {}
};

void non_constexpr() {}

constexpr bool bar()
{
  if (std::is_constant_evaluated()) {
  } else {
    non_constexpr();
    double d;
    reinterpret_cast<int*>(&d);
    Foo f;  // error: variable ‘f’ of non-literal type ‘Foo’ in ‘constexpr’ function
  }

  return true;
}

constexpr bool x = bar();

【问题讨论】:

    标签: c++ constexpr c++20


    【解决方案1】:

    有一个特定的限制。在这种情况下,constexpr 函数体的结构限制。

    [dcl.constexpr]

    3 constexpr 函数的定义应满足 以下要求:

    • 其函数体不应包含
      • 非文字类型或静态或线程存储持续时间的变量的定义。

    这就是它的长处和短处。如果您想知道为什么会这样,因为在持续评估中不会执行禁止的代码,那也是good question。不幸的是,我目前不知道那个的答案。这可能只是没有人想过要改变的事情。

    【讨论】:

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