我有一个 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/