Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use a concept for STL containers?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading