c++ - 将 find_if 和 boost::bind 与一组共享指针一起使用

标签 c++ boost shared-ptr boost-bind

我有一个 shared_ptr vector ,我想结合 boost shared_ptr 并绑定(bind)在一起。

我的问题与this 非常相似,除了我想调用“&Element::Fn”而不是“&MyClass::ReferenceFn”。

下面是一段类似的代码:

typedef boost::shared_ptr< Vertex > vertex_ptr; 
std::set<vertex_ptr> vertices;

void B::convert()
{
...
if( std::find_if(boost::make_indirect_iterator(vertices.begin()), 
                 boost::make_indirect_iterator(vertices.end() ),  boost::bind( &Vertex::id, boost::ref(*this), _1 ) == (*it)->id() ) == vertices.end() )
}

这里是错误:

no matching function for call to ‘bind(<unresolved overloaded function type>, const boost::reference_wrapper<B>, boost::arg<1>&)’

注意:我仅限于使用C++03。

最佳答案

要为存储在集合中的每个对象调用成员函数,您需要使用占位符作为 boost::bind 的第一个绑定(bind)参数。 :

boost::bind(&Vertex::id, _1) == (*it)->id())
//                       ~^~

这样,每个参数a , 将绑定(bind)到一个成员函数指针,并调用为 (a.*&Vertex::id)() .

但是,看到错误消息说 unresolved overloaded function type , 它得出的结论是你的类(class) Vertex可以有多个成员函数重载 id .因此,编译器无法判断应将哪一个作为 boost::bind 的参数传递.要解决这个问题,请使用对成员函数指针的显式转换(冒号后的星号表示它是指向成员的指针):

boost::bind(static_cast<int(Vertex::*)()const>(&Vertex::id), _1) == (*it)->id())
//                      ~~~~~~~~~~~~~~~~~~~~^

案例类Vertex有多个重载,比如:

int id() const { return 0; }
void id(int i) { }

您将使用第一个进行绑定(bind)。

关于c++ - 将 find_if 和 boost::bind 与一组共享指针一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36182694/

相关文章:

c++ - 使用 C++ 和 boost 生成泊松到达日期

c++ - 创建 shared_ptr 到堆栈对象

c++ - 当同名文件夹已存在时,如何使用 boost 创建新文件夹?

c++ - 如何只替换 CString 中第一次出现的字符?

c++ - 这是参数还是类型?

c++ - 抗锯齿不适用于 Windows

c++ - 如何正确使用带有公共(public)成员变量的类型的 boost::optional?

c++11 - 无法消除共享指针泄漏的递归解析代码

c++ - shared_ptr : what's it used for

c++ - MSVC : inference of pointer to member function with const and non-const overloads