Why do some STL algorithms provide an additional _if function instead of overloading?

Why do some STL algorithms provide an additional '_if' function instead of overloading?

 // example: find(beg, end, val); find_if(beg, end, pred); 

Could they just overload these algorithms instead of creating additional _if functions?

+7
c ++ c ++ 11 stl stl-algorithm
source share
2 answers

These algorithms provide a named version, not an overloaded one, since both versions of the algorithm accept the same number of arguments. Thus, an overload of ambiguities is possible.

To avoid possible ambiguities, the library provides separate named versions for these algorithms, find_if is one of them.

+11
source share

It is unclear how congestion resolution will work in general. What if, say, a container contains predicates?

 struct pred { bool operator()(const pred&) const; friend bool operator==(const pred&,const pred&); }; std::vector<pred> v; pred p; std::find(v.begin(), v.end(), p); // what should happen here? 

This potential ambiguity is eliminated due to the presence of functions with different names, with each name expressing its intent more clearly.

Note that this is a simplification: in std::find there is no requirement that the reference object be of the same type as the value_type container, just that they are comparable for equality. The predicate requirements in std::find_if are also common. Both of these functions are extremely common, which means that ambiguity can occur more easily than in the above example. For example,

 struct foo {}; struct pred { bool operator()(const foo&) const; }; bool operator==(const foo&, const pred&); int main() { std::vector<foo> v; pred p; std::find(v.begin(), v.end(), p); // What should this do? std::find_if(v.begin(), v.end(), p); // Here, it is clear. } 
+18
source share

All Articles