Vahagn
Vahagn

Reputation: 4820

How to define a recursive concept?

The cppreference.com states that:

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>>>);

But I want to have something like IIntX that will mean IIntN for any N.

Is it possible?

Upvotes: 19

Views: 2279

Answers (1)

Barry
Barry

Reputation: 302852

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

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

Upvotes: 23

Related Questions