c++ - "requires"忽略一个字段不是静态的

标签 c++ c++20 c++-concepts

考虑以下代码:

#include <iostream>

constexpr int fun(int const&) { return 5; }
struct T { int x; };

int main() {
  std::cout << fun(T::x) << std::endl;                   // Line A
  std::cout << requires { fun(T::x); } << std::endl;     // Line B
}
如果我只注释 B 行,则无法编译代码(正如预期的那样,因为 xT 中不是静态的)。但是,当我只注释 A 行时,代码在 Clang 11.0.0 和 GCC 10.2.0(均输出 1)下编译得很好。我想念的是什么 requires ?它不应该返回false ?

最佳答案

一个 requires 表达式是一大堆未计算的操作数。

[expr.prim.req]

2 A requires-expression is a prvalue of type bool whose value is described below. Expressions appearing within a requirement-body are unevaluated operands.


命名非静态数据成员的限定 ID 总是可以出现在未计算的操作数中。

[expr.prim.id]

2 An id-expression that denotes a non-static data member or non-static member function of a class can only be used:

  • as part of a class member access in which the object expression refers to the member's class or a class derived from that class, or

  • to form a pointer to member ([expr.unary.op]), or

  • if that id-expression denotes a non-static data member and it appears in an unevaluated operand. [ Example:

struct S {
  int m;
};
int i = sizeof(S::m);           // OK
int j = sizeof(S::m + 42);      // OK

— end example ]


未计算的操作数 where T::x可能出现可以是任何表达式。因此,即使是 C++20 之前的版本,您也可以编写
decltype(fun(T::x)) i{};

关于c++ - "requires"忽略一个字段不是静态的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64798455/

相关文章:

c++ - 无法使用 QtCreator #include <QWebView>

c++ - 我可以在 using 声明中正确使用 C++20 概念吗?

c++ - std::atomic<T>::wait 的 std::memory_order

c++ - 自 C++20 以来是否允许对分配的存储进行指针运算?

c++ - 使用 std::range::copy 和适配器打印 std::map

c++ - std::is_convertible和std::convertible_to(在实践中)之间的区别?

c++ - Placement new,对象放置在 I/O 寄存器和归零内存上

c++ - 在不控制线程的情况下同步 boost::thread 中的 STD cout 输出

c++ - 使用 include 定义枚举

c++ - 嵌套的依赖名称不在模板中评估概念