【发布时间】:2020-11-30 11:47:27
【问题描述】:
我正在观看 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>>);
【问题讨论】:
标签: c++ c++17 c++20 c++-concepts