如何绑定成员函数以与std :: for_each一起使用?

时间:2011-10-28 21:16:26

标签: c++ stl foreach bind

我的目标是在for_each电话中使用会员功能。所以我这样做了:

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

但这是我在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>&)'

在VS2010中,这个:

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

完整的源代码为here

任何帮助?

1 个答案:

答案 0 :(得分:4)

nurikabe::fill_adjacent实际上有两个参数 - nurikabe*cell - 但你只传递了第一个参数。使用cell的占位符,如下所示:

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

(请注意_1位于名称空间std::placeholders。)