“需要"忽略字段不是静态的 [英] "requires" ignores a field is not static
问题描述
考虑以下代码:
#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
吗?
If I only comment Line B, then the code cannot be compiled (as expected, since x
is not static in T
). But when I only comment Line A, the code compiles just fine with both Clang 11.0.0 and GCC 10.2.0 (both output 1
). What it is that I am missing about requires
? shouldn't it return false
?
推荐答案
要求表达式是一大堆未评估的操作数.
A requires expression is one big list of unevaluated operands.
[expr.prim.req]
2 require-expression是类型为bool的prvalue,其值为如下面所描述的.出现在需求主体中的表达式是未评估的操作数.
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总是可能出现在未评估的操作数中.
And a qualified-id naming a non-static data member always could appear in an unevaluated operand.
[expr.prim.id]
2 表示以下内容的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
形成指向成员([expr.unary.op])的指针,或
to form a pointer to member ([expr.unary.op]), or
如果该id表达式表示一个非静态数据成员,并且它出现在未评估的操作数中.[示例:
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
—结束示例]
可能出现 T :: x
的未经评估的操作数可以是任何表达式.因此,即使在C ++ 20之前的版本中,您也可以编写
The unevaluated operand where T::x
may appear can be any expression. So even pre-C++20 you could for example write
decltype(fun(T::x)) i{};
这篇关于“需要"忽略字段不是静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!