考虑以下代码:
#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 行,则无法编译代码(正如预期的那样,因为 x
在 T
中不是静态的)。但是,当我只注释 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/