如何定义递归概念? [英] How to define a recursive concept?

查看:28
本文介绍了如何定义递归概念?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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>> { };

这篇关于如何定义递归概念?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆