如何定义递归概念

How to define a recursive concept?

本文关键字:递归 定义 何定义      更新时间:2023-10-16

cppreference.com指出:

概念不能递归地提及自己

但是,我们如何定义一个代表整数或整数的向量的概念,或整数的向量,等等。

我可以有这样的东西:

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

可能吗?

概念始终可以推迟到类型特征:

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,则可以将最后一个部分专业化推广到:

template <std::Range R>
struct some_trait<R> : some_trait<std::range_value_t<R>> { };