about passing a Predicate as template argument

1.4k Views Asked by At

I coded a generic function template like below that doesn't build.

It builds only if the predicate is passeed by const reference or by value.

Do you know what principle C++ is following in this case?

I am using g++ and my version doesn't have C++11 available.

I've checked on what boost::bind returns and it says unspecified type (I hope to have read properly).

 struct MyRecord{
   int a_;
   int b_;
 };

 template<class Predicate>
 bool isAny(Predicate &pred) {
  vector<MyRecord>::iterator it = std::find_if(
           records.begin(), 
           records.end(), 
           pred);
  if(it!=records.end()) {
   // .. do something
  }
  return it != records.end();
 }

 isAny(boost::bind(&MyRecord::a_,_1)==1);
 isAny(boost::bind(&MyRecord::b_,_1)==2);

 // It works with the 2 declarations below
 template<class Predicate>
 bool isAny(const Predicate &pred);

 // or

 template<class Predicate>
 bool isAny(Predicate pred);
1

There are 1 best solutions below

1
On BEST ANSWER

Your call isAny(boost::bind(&MyRecord::a_,_1)==1); creates a temporary object. In C++, a temporary can only bind to a const reference parameter or to a value parameter. The idea is that if a function takes an argument by non-const reference it means to modify the parameter, and modifying a temporary would be meaningless.

FWIW STL takes predicates by value.