1

In C++ stl, there is e.g.:

template<class InputIt, class UnaryPredicate>
constexpr InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );

My question is: why there is not:

... find_if(..., UnaryPredicate &&p);

In my understanding it would be more "universal". R-value predicates still would be passed by value. Additionally, L-value predicates could be passed too:

struct MyComplexPred { 
  MyComplexPred(MyComplexPred const &) = delete; // expensive/"impossible" copy
  MyComplexPred() { /*...*/ }
  bool operator()(int val) const { return true; /*...*/ }
};
int fun() {
  MyComplexPred pred;
  std::vector<int> a, b;
  std::find_if(a.begin(), a.end(), pred);  // impossible, no copy
  std::find_if(b.begin(), b.end(), pred);  // impossible, reuse predicate
  ...

I found a similar question here but I wonder why the suggested &&-passing with reference collapsing is not used in stl for predicates and other function objects.

Jarek C
  • 1,077
  • 6
  • 18
  • My guess, the standard allows the predicate to be copied by the algorithm. Having the pass by value is an easy way to enforce that the predicate is copyable. – NathanOliver Jun 23 '20 at 14:08
  • 3
    Seems related https://stackoverflow.com/questions/48803927/why-does-stdfind-iffirst-last-p-not-take-predicate-by-reference – StoryTeller - Unslander Monica Jun 23 '20 at 14:08
  • In the linked question I found this answer: "Pass by reference (T&) doesn't work for temporary or const objects, T const& doesn't work for non-const&, i.e., the only choice would be T&& (forwarding reference) which didn't exist pre-C++11 and the algorithm interfaces didn't change since they were introduced with C++98." so I believe it is still true. – Jarek C Jun 23 '20 at 14:32

0 Answers0