gpt4 book ai didi

不完整类上下文中的 C++ 概念检查

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

请考虑一个 C++20 概念程序:

struct A {};

template<typename T>
concept DerivedOnceFromA = requires(T t) { { static_cast<const A&>(t) }; };

template<DerivedOnceFromA T>
struct B {};

struct C : A
{
B<C> foo();
};

这里是概念DerivedOnceFromA检查 T可以静态转换为 A . B是遵循这个概念的模板结构。和结构 C源自 A (因此这个概念得到满足)并定义了一个返回 B<C> 的函数.

此代码被 GCC 和 MSVC 接受,但被 Clang 拒绝并出现错误:

constraints not satisfied for class template 'B' [with T = C]

演示:https://gcc.godbolt.org/z/7Tc7xdbeq

在类体内使用类作为概念模板参数是否合法(那么哪个编译器是正确的)?

最佳答案

合法吗?是的,它在范围内。但是您无法从中收集到太多有用的信息。

[class.mem.general]

6 A complete-class context of a class is a

  • function body ([dcl.fct.def.general]),
  • default argument,
  • noexcept-specifier ([except.spec]), or
  • default member initializer within the member-specification of the class.

7 A class is considered a completely-defined object type([basic.types]) (or complete type) at the closing } of theclass-specifier. The class is regarded as complete within itscomplete-class contexts; otherwise it is regarded as incomplete withinits own class member-specification.

所以你在使用它的时候它仍然被认为是不完整的,最多只是你转发声明的一种类型。因此,无论启用转换的机制(继承或用户定义的转换运算符)如何,您都不知道它是否可以转换为其他引用。即使借助像 std::derived_from 这样的标准概念,也无法知道一个不完整的类型是否派生自 A。不完整类型的可观察属性非常有限。

关于不完整类上下文中的 C++ 概念检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68521370/

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