Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Many standard library algorithms have two versions in C++20: one in the std namespace and another one in the std::ranges namespace with the same name. For example, std::ranges::count and std::count are both are used to count the number of elements that satisfy a predicate.

Why are there two versions of these algorithms?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
225 views
Welcome To Ask or Share your Answers For Others

1 Answer

The Ranges functionality adds C++20 concepts to iterators and ranges, and it constrains the definition of its algorithms and the like to those concepts. However, the C++20 concepts have different requirements from the C++17 named requirements. Usually, types which fulfilled the C++17 requirements will fulfill the C++20 concept equivalents, but not in all cases1. And while it is usually easy enough to update your own code to be valid for C++20 concepts, it would still break backwards compatibility for user-written iterators to just stop compiling in C++20.

So instead of imposing constrained algorithms on the user, they created new algorithms that you can choose to use instead. Thus, no code breakage.

1: Also, because C++17's requirements were never actually checked by anything, it was really easy to accidentally write an iterator that didn't entirely implement their requirements. The algorithms you use could just not actually use the the functionality you didn't implement, thus giving the appearance that you implemented what you needed to. This is especially true if you didn't test the code against more than one standard library implementation. If C++20 started checking your iterators, it would suddenly break your technically-broken-yet-functional code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...