【问题标题】:Using find_if and boost::bind with a set of shared_pointers将 find_if 和 boost::bind 与一组 shared_pointers 一起使用
【发布时间】:2016-03-23 15:45:50
【问题描述】:

我有一个 shared_ptr 的向量,我想结合 boost shared_ptr 并绑定在一起。

我的问题与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。

【问题讨论】:

  • 你得到什么错误?
  • @PiotrSkotnicki,错误是它把(this关键字)作为B类的this指针
  • 然后你想要boost::bind(&amp;Vertex::id, _1) == (*it)-&gt;id()),或者boost::bind(static_cast&lt;int(Vertex::*)()&gt;(&amp;Vertex::id), _1) == (*it)-&gt;id())(其中intid的返回类型)
  • 非常感谢,如果您提供评论作为答案,我会选择它作为最佳解决方案。另外请您解释一下“(Vertex::*) 中的星号是什么意思?

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


【解决方案1】:

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

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

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

但是,看到错误消息显示unresolved overloaded function type,它得出的结论是您的类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) { }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2023-04-07
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    相关资源
    最近更新 更多