gpt4 book ai didi

c++ - 为什么双重否定会改变 C++ 概念的值(value)?

转载 作者:行者123 更新时间:2023-12-04 07:03:04 25 4
gpt4 key购买 nike

我的一个 friend 向我展示了一个带有概念的 C++20 程序,这让我感到困惑:

struct A { static constexpr bool a = true; };

template <typename T>
concept C = T::a || T::b;

template <typename T>
concept D = !!(T::a || T::b);

static_assert( C<A> );
static_assert( !D<A> );
它被所有编译器接受: https://gcc.godbolt.org/z/e67qKoqce
这里的概念 D同概念 C ,唯一的区别在于双重否定运算符 !! , 乍一看不应改变概念值。仍然用于结构 A概念 C是真的和概念 D是假的。
你能解释一下为什么会这样吗?

最佳答案

Here the concept D is the same as the concept C


他们不是。当检查满意度并分解为原子约束时,约束(和概念 ID)被规范化。

[temp.names]

8 A concept-id is a simple-template-id where the template-name isa concept-name. A concept-id is a prvalue of type bool, and does notname a template specialization. A concept-id evaluates to true if theconcept's normalized constraint-expression ([temp.constr.decl]) issatisfied ([temp.constr.constr]) by the specified template argumentsand false otherwise.


||C 中被区别对待和 D :

[temp.constr.normal]

2 The normal form of an expression E is a constraint that is definedas follows:

  • The normal form of an expression ( E ) is the normal form of E.
  • The normal form of an expression E1 || E2 is the disjunction of the normal forms of E1 and E2.
  • The normal form of an expression E1 && E2 is the conjunction of the normal forms of E1 and E2.
  • The normal form of a concept-id C<A1, A2, ..., An> is the normal form of the constraint-expression of C, after substituting A1,A2, ..., An for C's respective template parameters in theparameter mappings in each atomic constraint. If any such substitutionresults in an invalid type or expression, the program is ill-formed;no diagnostic is required.
  • The normal form of any other expression E is the atomic constraint whose expression is E and whose parameter mapping is the identitymapping.

对于 C原子约束是 T::aT::b .
对于 D只有一个原子约束是 !!(T::a || T::b) .
原子约束中的替换失败使其不满足并评估为 false . C<A>是一个满足的约束和一个不满足的约束的分离,所以它是 true . D<A>是假的,因为它的一个也是唯一的原子约束有一个替换失败。

关于c++ - 为什么双重否定会改变 C++ 概念的值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68601659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com