Big*_*eny 5 c++ c++-concepts c++17 c++20
我正在观看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>>);
Run Code Online (Sandbox Code Playgroud)
复合要求
{ e } -> Concept;
Run Code Online (Sandbox Code Playgroud)
意味着这e必须是一个有效的表达式并且Concept<decltype((e))>必须成立。注意双括号,这很重要。让我们看一个更简单的树,我不知道为什么这需要一个模板:
struct X {
int root;
};
X t;
Run Code Online (Sandbox Code Playgroud)
虽然decltype(t.root)is int(该成员变量的声明类型为int),decltype((r.root))is int&(因为它是类型 的左值int,因此int&)。因此:
template <typename T>
concept Tree = requires(T t) {
{ t.root } -> std::same_as<int&>;
};
Run Code Online (Sandbox Code Playgroud)
Tree<X>成立 - 因为t.root是 类型的左值int。
clang 根本就搞错了。它没有实现P1084,这是#45088。