简体   繁体   中英

about passing a Predicate as template argument

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM