How to define a recursive concept?(如何定义递归概念?)
问题描述
cppreference.com 指出:
概念不能递归地引用自己
Concepts cannot recursively refer to themselves
但是我们如何定义一个概念来表示整数或整数向量,或整数向量的向量等.
But how can we define a concept that will represent an integer or a vector of integers, or a vector of vector of integers, etc.
我可以拥有这样的东西:
I can have something this:
template < typename Type > concept bool IInt0 = std::is_integral_v<Type>;
template < typename Type > concept bool IInt1 = IInt0<Type> || requires(Type tt) { {*std::begin(tt)} -> IInt0; };
template < typename Type > concept bool IInt2 = IInt1<Type> || requires(Type tt) { {*std::begin(tt)} -> IInt1; };
static_assert(IInt2<int>);
static_assert(IInt2<std::vector<int>>);
static_assert(IInt2<std::vector<std::vector<int>>>);
但我想要像 IIntX
这样的东西,这意味着任何 N 的 IIntN.
But I want to have something like IIntX
that will mean IIntN for any N.
有可能吗?
推荐答案
概念总是可以遵从类型特征:
Concepts can always defer to a type trait:
template <typename T> concept C = some_trait<T>::value;
而且这个特征可以递归:
And that trait can be recursive:
template <typename T>
struct some_trait : std::false_type { };
template <std::Integral T>
struct some_trait<T> : std::true_type { };
template <typename T, typename A>
struct some_trait<std::vector<T, A>> : some_trait<T> { };
如果你的意思不只是vector
,那么最后的部分特化可以推广为:
If you don't mean just vector
, then the last partial specialization can be generalized to:
template <std::Range R>
struct some_trait<R> : some_trait<std::range_value_t<R>> { };
这篇关于如何定义递归概念?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何定义递归概念?


- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01