"requires"什么时候会导致编译错误

When does "requires" cause a compiler error

考虑这段代码:

struct Bad {};

int main() {
    static_assert(requires(int n, Bad bad) { n += bad; });
}

使用 Clang 13 和 -std=c++20 编译时,出现以下错误:

<source>:5:48: error: invalid operands to binary expression ('int' and 'Bad')
    static_assert(requires(int n, Bad bad) { n += bad; });
                                             ~ ^  ~~~
1 error generated.

但我希望 requires 表达式为 return false 并使 static_assert.

失败

如果我将这个概念重写为模板约束,我会得到我期望的条件编译,即编译器不会抱怨没有 operator+= 并且要求 return 为假。

一个notation from the standard:

If a requires-expression contains invalid types or expressions in its requirements, and it does not appear within the declaration of a templated entity, then the program is ill-formed.

所以requires只有在模板中时才会获得此功能。