jeffbRTC
jeffbRTC

Reputation: 2069

What are the use cases of C++20 Concepts?

I found about Concepts while reviewing C++20 features. I found that they add validation to templates arguments but apart from that I don't understand what are the real world use cases of C++20 concepts.

C++ already has things like std::is_integral and they can perform validation very well.

I'm sure I am missing something about C++20 concepts and what it enables.

Upvotes: 7

Views: 1511

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

SFINAE (see here & here) was an accidentally Turing complete sublanguage that executes at overload resolution and template specialization selection time.

Turns out it is used a lot in template code.

Concepts and requires clauses are an attempt to take that accidentally useful language feature and make it suck less.

The origin of concepts was going to have 3 pieces; (a) describing what is required for a given bit of template code in a clean way, (b) also provide a way to map other types to satisfy those requirements non-intrusively, and (c) check template code so that any type which satisfies the concept is guaranteed to compile

All attempts at (a) plus (c) sucked, usually taking forever to compile and/or restricting what you can check with (a). (b) was also dropped to ensure (a) was better; you can write such concept map machinery manually in many cases, but C++ doesn't provide it for you.

So, now what is it good for?

auto sum( Addable auto... values )

that uses the concept of Addable to concisely express an interface of a template. Error messages you get when passing a non-addable highlight it isn't Addable, and the expression that doesn't work.

template<class T, class A>
struct vector{
  bool operator==(vector<t,A>const& o)requires EquallyComparible<T>;
};

here, we state this vector has a == if and only if the T does. Doing this before concepts is an annoying undertaking, and even adding the specs to the standard is.

This is the turing tar pit; everyting is equivalent, but nothing is easy. All programs can be written with I/O plus a (a=(a-b);(a<0)?goto c:next 3 argument instruction; but a richer language makes programs suck less. Concepts takes an esoteric branch of C++, SFINAE, and makes it clean and simpler (so more people can leverage it), and improves error messages.

Upvotes: 12

Related Questions