如何定义一个递归概念? [英] 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.
我可以吃点东西
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表示IInt N .
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;
该特征可以递归:
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>> { };
这篇关于如何定义一个递归概念?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文