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

标签 c++ c++17 c++20 c++-concepts

我在看 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/

相关文章:

c++ - 自己的 vector 分配实现

c++ - 子模块 : how to divide C++ module into submodules

c++ - 不能包含 std::format

c++ - "T a"、 "T a()"和 "T a=T()"之间有什么区别,其中 T 是一个类?

c++ - CUDA channel ID 与基于 threadIdx.x 的计算

c++ - 调试断言失败 : string subscript out of range

c++ - 显式直接#include 与非契约传递#include

c++ - GCC7 在同一个类中推断出存在 const 修饰符

c++ - 如何使用折叠表达式调用成员函数链

c++ - 如何对 vector <char*> 进行排序?