Home > OS >  Using a concept in another concept's 'requires' clause
Using a concept in another concept's 'requires' clause

Time:11-25

I have a fairly simple example that I'm struggling with. I'd like to use an already-defined concept in another concept's requires clause - something like this, except actually working:

template<typename T>
concept Any = true;

template<typename T>
concept UsesAnyA = requires(T t, Any auto a) {
  t(a);
};

I've also tried defining UsesAny like this, to no further avail:

template<typename T, Any A>
concept UsesAnyB = requires(T t, A a) {
  t(a);
};

From a conceptual (...sorry) angle it feels like this should be possible. Can anyone suggest something?

CodePudding user response:

Probably need to do something like this:

template <typename T>
concept Any = true;

template <typename T, typename A>
concept UsesAny = Any<A> and requires (T t, A a) {
  t(a);
};

A concept needs each of the complete types involved in order to test its constraint, but at the point you evaluate it, you should already have the complete types available to test with.

I realize checking Any<A> in this example is redundant, but I'm assuming your actual concept is not trivial, and this demonstrates how to use it to constrain your dependent concept.

Here are the three different ways you can constrain a template with UsesAny:

template <typename A>
auto f(A a, UsesAny<A> auto t) { t(a); }

template <typename A, UsesAny<A> T>
auto f(A a, T t) { t(a); }

template <typename A, typename T>
requires UsesAny<T, A>
auto f(A a, T t) { t(a); }

each of these forms are equivalent.

  • Related