[英]Why are parentheses needed around negated expressions in a requires-clause?
The following code is an usage example of the requires
-clause:以下代码是requires
子句的使用示例:
#include <type_traits>
template <typename T>
requires std::is_integral_v<T>
void take_integral(T value);
It accepts an expression that evalutes to a bool
value ( std::is_integral_v<T>
in this case), and works as expected.它接受一个计算为bool
值的表达式(在本例中为std::is_integral_v<T>
),并按预期工作。 However, when such expression is negated with the !
然而,当这样的表达式被!
operator, it results in a compilation error:运算符,它会导致编译错误:
#include <type_traits>
template <typename T>
requires !std::is_integral_v<T>
void take_integral(T value);
Diagnostic from GCC:来自 GCC 的诊断:
<source>:4:12: error: expression must be enclosed in parentheses
4 | requires !std::is_integral_v<T>
| ^~~~~~~~~~~~~~~~~~~~~~
| ( )
Compiler returned: 1
Diagnostic from Clang:来自 Clang 的诊断:
<source>:4:12: error: parentheses are required around this expression in a requires clause
requires !std::is_integral_v<T>
^~~~~~~~~~~~~~~~~~~~~~
( )
1 error generated.
Compiler returned: 1
Why are parentheses needed here?为什么这里需要括号?
Parentheses are required because they avoid language parsing ambiguities.括号是必需的,因为它们可以避免语言解析歧义。
Not every expression is allowed inside a requires
-clause.并非所有表达式都允许在requires
子句中。 In fact, the standard gives an example of how a parsing ambiguity would arise if all expressions were allowed:事实上,该标准给出了一个示例,说明如果允许所有表达式,将如何产生解析歧义:
[...] The expression in a requires-clause uses a restricted grammar to avoid ambiguities. [...] requires 子句中的表达式使用受限制的语法来避免歧义。 Parentheses can be used to specify arbitrary expressions in a requires-clause .括号可用于在requires 子句中指定任意表达式。 [ Example: [ 例子:
template<int N> requires N == sizeof new unsigned short int f(); // error: parentheses required around == expression
— end example ] — 结束示例 ]
In the above example given by the standard, a compiler couldn't possibly know whether the sizeof
part should be parsed as a sizeof
of the expression new unsigned short
or new unsigned short int
.在标准给出的上述示例中,编译器不可能知道是否应该将sizeof
部分解析为表达式new unsigned short
或new unsigned short int
的sizeof
。 Putting parentheses around it, like requires (N == sizeof new unsigned short)
, solves the problem.在它周围加上括号,比如requires (N == sizeof new unsigned short)
,解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.