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>> { };
这篇关于如何定义递归概念?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何定义递归概念?
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
