Search code examples
c++c++-concepts

Is it possible to pass a concept as a template parameter?


Is it possible to pass a concept as a template parameter? For example:

I want to do something like this:

template <typename t, typename u> concept range_of =
    range<t> &&
    requires (t a) {
        {*a.begin()} -> std::same_as<u &>;
    };

But instead of giving the exact type u I want to give it a concept:

template <typename t, {{concept u}}> concept constrained_range =
    range<t> &&
    requires (t a) {
        {*a.begin()} -> u;
    };

Solution

  • It's possible to cheat a bit since we can pass lambda functions as template arguments ; a concept is just a meta-function from the domain of types to the boolean domain after all.

    Here is an example:

    template<auto F, typename T>
    using check = std::conditional_t<
          F.template operator()<T>()
        , std::true_type
        , std::false_type>;
    
    #define CONCEPT(TheConcept) \
      [] <typename T> () consteval { return TheConcept<T>; }
    
    static_assert(check<CONCEPT(std::floating_point), float>::value);
    

    Demo on Godbolt: https://gcc.godbolt.org/z/fGf45nqTc