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

3
我的目标是在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 '::'

完整的源代码可以在这里找到。
需要帮助吗?
1个回答

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 中。)

1
@vivek:没错,这就是我提到它所在的命名空间的原因——这样你就知道如何完全限定它或者为哪个命名空间创建using指令了。:-] - ildjarn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接