Home > Software engineering >  How to use a concept for STL containers?
How to use a concept for STL containers?

Time:03-11

Based on this old stack overflow question How do you define a C concept for the standard library containers?

I see that it's possible to define a concept for STL containers. However, I am unsure how to actually apply the concept to anything, because it requires 2 containers, container a and container b.

For example, taking the signature of the most upvoted answer

template <class ContainerType> 
    concept Container = requires(ContainerType a, const ContainerType b) 

I've only seen concepts used with just 1 requirement argument, like so

//source: https://en.cppreference.com/w/cpp/language/constraints
template<typename T>
concept Hashable = requires(T a)
{
    { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;
};
 
struct meow {};
 
// Constrained C  20 function template:
template<Hashable T>
void f(T) {}
//
// Alternative ways to apply the same constraint:
// template<typename T>
//     requires Hashable<T>
// void f(T) {}
//
// template<typename T>
// void f(T) requires Hashable<T> {}
 
int main()
{
    using std::operator""s;
 
    f("abc"s);    // OK, std::string satisfies Hashable
    // f(meow{}); // Error: meow does not satisfy Hashable
}

CodePudding user response:

The definition of this concept is in fact

 template <class ContainerType> 
 concept Container = /* */;

which only constrains one type ContainerType, so the function that applies this concept would be

 template <Container C>
 void f(C& c);
  • Related