gpt4 book ai didi

c++ - 如何在概念中使用 C++ requires 子句来要求成员变量满足概念约束?

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

我在看 C++ 20 Concepts Presentation ,并且在尝试重现代码时,我似乎被卡住了。
我试图要求树的根应该满足 MyObjConcept0_,为简单起见,它只是一个 int。为什么当我在 Tree_ 概念的 requires 子句中使用这个概念时,结果是错误的?
我试图直接从演示文稿中复制代码,但仍然没有运气。为什么 { t.root } 子句的返回类型是 int& - 我的意思是这是有道理的,因为当您以这种方式访问​​成员时,您将获得一个引用。
那么如何在 39:00 的演示中出现 this(与 MyObjConcept0_ 相同)需要子句通过?
从本次演示的角度来看,标准是否有所改变,还是我盲目地遗漏了什么?

#include <concepts>
#include <functional>

// Type is an int
template<typename T>
concept MyObjConcept0_ = std::same_as<T,int>;

// Type is any type that decays to int
template<typename T>
concept MyObjConcept1_ = std::same_as<std::decay_t<T>,int>;

// Type is an int&
template<typename T>
concept MyObjConcept2_ = std::same_as<T,int&>;



template<typename T>
concept Tree_ = requires (T t) {
{ t.root } -> MyObjConcept0_; // does not work : This is the concept I want to use
{ t.root } -> MyObjConcept1_; // works but will pass for int and int& : unsafe
{ t.root } -> MyObjConcept2_; // works but checks that t.root is an int&
std::same_as<decltype(t.root),int>; // works: verbose and not a concept
};

template<MyObjConcept0_ MyObjConcept0T>
struct tree {
MyObjConcept0T root;
};

static_assert(Tree_<tree<int>>);

最佳答案

复合要求

{ e } -> Concept;
意味着 e必须是有效的表达式并且 Concept<decltype((e))>必须坚持。注意双括号,这很重要。就拿一个更简单的树来说吧,不知道为什么这需要一个模板:
struct X {
int root;
};

X t;
虽然 decltype(t.root)int (该成员变量的声明类型是 int ), decltype((r.root))int& (因为它是 int 类型的左值,因此是 int& )。其结果:
template <typename T>
concept Tree = requires(T t) {
{ t.root } -> std::same_as<int&>;
};
Tree<X>持有 - 因为 t.rootint 类型的左值.

clang 只是弄错了。它没有实现 P1084 , 这是 #45088 .

关于c++ - 如何在概念中使用 C++ requires 子句来要求成员变量满足概念约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63347537/

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