简体   繁体   中英

How do I bind a member function for use with std::for_each?

My aim is to use a member function in a for_each call. So I did it like this:

for_each(an_island->cells.cbegin(),an_island->cells.cend(),std::bind(&nurikabe::fill_adjacent,this));

but this is what I get in GCC:

In file included from /usr/lib/gcc/i686-pc-linux-gnu/4.5.1/../../../../include/c++/4.5.1/algorithm:63:0,
                 from prog.cpp:10:
/usr/lib/gcc/i686-pc-linux-gnu/4.5.1/../../../../include/c++/4.5.1/bits/stl_algo.h: In function '_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = std::_Rb_tree_const_iterator<std::pair<int, int> >, _Funct = std::_Bind<std::_Mem_fn<int (nurikabe::*)(std::pair<int, int>)>(nurikabe*)>]':
prog.cpp:85:103:   instantiated from here
/usr/lib/gcc/i686-pc-linux-gnu/4.5.1/../../../../include/c++/4.5.1/bits/stl_algo.h:4185:2: error: no match for call to '(std::_Bind<std::_Mem_fn<int (nurikabe::*)(std::pair<int, int>)>(nurikabe*)>) (const std::pair<int, int>&)'

and in VS2010, this :

xxresult(28): error C2825: '_Fty': must be a class or namespace when followed by '::'

The full souce code is here

Any help ?

nurikabe::fill_adjacent effectively takes two arguments -- a nurikabe* and a cell -- but you're only passing the first. Use a placeholder for cell , like so:

for_each(
    an_island->cells.cbegin(),
    an_island->cells.cend(),
    std::bind(&nurikabe::fill_adjacent, this, _1)
);

(Note that _1 resides in namespace std::placeholders .)

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