std::bind, this and QtConcurrent

3

我正在尝试使用std::bindthis绑定到在QtConcurrent::blockingMapped中使用的方法。

头文件:

class TuringMachine
{
private:
    TRTable table;
    std::set<ConfigNode*> currentConfigs;

    //function object
    std::function<std::set<ConfigNode*>( const TuringMachine*, ConfigNode*)> step_f;
    //method it will hold
    std::set<ConfigNode *> step(TuringMachine* this_m ,ConfigNode *parent);

    std::set<ConfigNode*>& makeStep();

}

Source:

    TuringMachine::TuringMachine(/**/)  
{

    step_f = std::bind(&TuringMachine::step, this, std::placeholders::_1);
}

std::set<ConfigNode*> &TuringMachine::makeStep(){

    auto configSet = QtConcurrent::blockingMapped<QLinkedList<std::set<ConfigNode*>>>(currentConfigs, step_f);//concurrent execution!

   /**/ 
   return currentConfigs;
}
std::set<ConfigNode*> TuringMachine::step(TuringMachine *this_m, ConfigNode * parent){     //the actual step
  /**/
}

我所做的是并行运行步骤,与currentConfigs中的每个ConfigNode上的blockingMapped同时运行。我使用std::bindthis绑定到step,使其只需要一个参数,就像blockingMapped的文档中所述。

我得到的结果是:

error: no match for call to '(std::_Bind<std::_Mem_fn<std::set<ConfigNode*> (TuringMachine::*)(TuringMachine*, ConfigNode*)>(TuringMachine*, std::_Placeholder<1>)>) (const TuringMachine*, ConfigNode*)'
.../Qt/474/gcc/include/QtCore/qtconcurrentmapkernel.h:121: error: no match for call to '(std::function<std::set<ConfigNode*>(const TuringMachine*, ConfigNode*)>) (ConfigNode* const&)'
.../Qt/474/gcc/include/QtCore/qtconcurrentmapkernel.h:136: error: no match for call to '(std::function<std::set<ConfigNode*>(const TuringMachine*, ConfigNode*)>) (ConfigNode* const&)'

并且 注意:需要2个参数,但只提供了1个

我哪里错了?

编辑

已纠正,可工作版本(供将来“参考”):

头部:

    //function object
    std::function<std::set<ConfigNode*>( ConfigNode*)> step_f;
    //method it will hold
    std::set<ConfigNode *> step(ConfigNode *parent);

来源:

    TuringMachine::TuringMachine(/**/)  
{
    step_f = std::bind(&TuringMachine::step, this, std::placeholders::_1);
}
1个回答

3
如果你想绑定一个成员函数,你需要传递一个指向this的指针,而在你的情况下这意味着你需要传递两个this指针:

成员函数的正常调用:

struct bar {
  int a;
  void foo() {
    std::cout << a << std::endl;
  }

  void call_yourself() {
     auto f = std::bind(&bar::foo, this);
     f();
  }
};

你的情况:

    step_f = std::bind(&TuringMachine::step, this, this,std::placeholders::_1);

如果我不了解你的代码,我可能会重新设计你的代码,以便避免双重this指针。


为什么需要第二个 this - TeaOverflow
@Evgeni,首先需要调用成员函数,因为这样做时,第二个参数需要是指向类的指针,该类是您的成员函数源或直接是您的类的对象。例如,您还可以说std::bind(&foo::bar, bar()) - Stephan Dollberg
我基本上想要做的是在多个ConfigNode对象上并发运行stepblockingMapped似乎是个好主意,因为它就是这样做的。但是我不能只使用成员函数,如此处所示。我必须将其绑定或使其成为静态/全局函数。 - TeaOverflow
1
我消除了这个“this”的重复。结果发现我不需要将“this”传递给该方法。谁知道呢 :-P。现在变成了step_f = bind(&TuringMachine::step, this, placeholders::_1);,它可以工作了。谢谢 - TeaOverflow

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