c++ - How does bind know when to cast to pointer? -


i found interesting thing in c++.

using namespace std;  struct person {     string name;      bool check() {         return name == "carol";     } };  int main() {     person p = { "mark" };     list<person> l;     l.push_back(p);      if (find_if(l.begin(), l.end(), bind(&person::check, std::placeholders::_1)) == l.end())     {         cout << "not found";     }     return 0; } 

the if statement above works should. while dereferencing iterator for_each gets , object , passes function. somehow bind knows (while biniding) first argument of pointer-to-member-function should pointer. in following example doesn't know , throws error due casting person person*. how bind work then? , how pass pointer in following example?

find_if(l.begin(), l.end(), bind(mem_fun(&person::check), std::placeholders::_1)) == l.end() 

i have come i'm not sure if best way of doing it.

find_if(l.begin(), l.end(), bind([](person& p) { return p.check(); }, std::placeholders::_1)) == l.end() 

the error you're seeing has nothing bind, it's mem_fun's (which deprecated, , removed in next version of c++) fault. when wrap pointer member function mem_fun, you're required pass pointer instance want invoke member function on.

find_if dereference iterator , pass result predicate, means you're trying pass person& instead of person* mem_fun_t. if want pass reference, use mem_fun_ref instead. following compile

find_if(l.begin(), l.end(), bind(mem_fun_ref(&person::check), std::placeholders::_1)) //                               ^^^^^^^^^^^ 

as barry points out, don't need bind in expression, following works too

find_if(l.begin(), l.end(), mem_fun_ref(&person::check)) 

or use mem_fun/mem_fun_ref's c++11 replacement, mem_fn

find_if(l.begin(), l.end(), mem_fn(&person::check)) 

finally, lambda expression can used

find_if(l.begin(), l.end(), [](person& p) { return p.check(); }) 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -