Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...