如何将C ++ 20约束的几种返回类型需求合并为一个返回类型需求? [英] How can I combine several return type requirements of C++20 constraints into one return type requirement?
问题描述
当前,我已经实现了 Allocator 概念(指提高建议 a>)使用C ++ 20 约束和概念 :
Currently, I have implemented the Allocator concept (which refers to the Boost proposal) using C++20 constraints and concepts:
#include <concepts>
#include <iterator>
template <class A>
concept allocator =
std::copy_constructible<A> &&
std::equality_comparable<A> &&
requires(A a) {
{ a.allocate(0) } -> std::regular;
{ a.allocate(0) } -> std::constructible_from<std::nullptr_t>;
{ a.allocate(0) } -> std::equality_comparable_with<std::nullptr_t>;
{ a.allocate(0) } -> std::random_access_iterator;
{ *a.allocate(0) } -> std::same_as<typename A::value_type&>;
};
您可以看到对于同一<$ c,有多个 return-type-requirement $ c>分配函数。有什么方法可以将它们组合成一个单一的 return-type-requirement ,如下所示?
You can see there are several return-type-requirements for the same allocate
function. Is there some way to combine them into one single return-type-requirement like the following?
{ a.allocate(0) } -> std::regular &&
std::constructible_from<std::nullptr_t> &&
std::equality_comparable_with<std::nullptr_t> &&
std::random_access_iterator;
推荐答案
对于这种特殊情况,您应该遵循更多概念密切。 allocator_traits< A> :: allocate
的返回类型必须为 allocator_traits< A> :: pointer
。这就是您应该测试的内容。 allocator_traits< A> :: pointer
必须满足连续迭代器和可为空指针的各种约束。
For this particular case, you should follow the concept more closely. The return type of allocator_traits<A>::allocate
is required to be allocator_traits<A>::pointer
. So that's what you should test. It is allocator_traits<A>::pointer
that must satisfy the various constraints of contiguous iterator and nullable pointer.
因此代码应该看起来像这样:
So the code should look like this:
template<typename P>
concept nullable_pointer =
std::regular<P> &&
std::convertible_to<std::nullptr_t, P> &&
std::assignable_from<P&, std::nullptr_t> &&
std::equality_comparable_with<P, std::nullptr_t>
template<typename P>
concept allocator_pointer =
nullable_pointer<P> &&
std::contiguous_iterator<P>;
template<typename A>
concept allocator =
std::copy_constructible<A> &&
std::equality_comparable<A> &&
requires(A a)
{
{ a.allocate(0) } -> allocator_pointer;
};
这篇关于如何将C ++ 20约束的几种返回类型需求合并为一个返回类型需求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!