2017-07-09 180 views
0

我有一个类Foo含有Bar s的vectorC++矢量的push_back与函数指针

class Foo 
{ 
public: 
    void create(); 
    void callback(); 

    std::vector<Bar> mBars; 
} 

Bar类包含此构造:

class Bar 
{ 
    Bar(const int x, const int y, std::function<void()> &callback); 
} 

Foo类有一个create()方法,将Bar s添加到mBars向量中:

void Foo::create() 
{ 
    mBars.push_back({ 1224, 26, callback }); //ERROR! 
} 

如何设置函数指针,使用std::function?也没有创建一个单独的对象和push_back成矢量?像上面的线,在那里我得到的错误:

E0304 no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=CV::Button, _Alloc=std::allocator<Bar>]" matches the argument list  
+1

你没有拿这个函数的指针。另外对于'std :: function',你必须使用'std :: bind'。 – tambre

+0

另外,您可能想查看['vector :: emplace_back()'](http://en.cppreference.com/w/cpp/container/vector/emplace_back)。 –

回答

4

callback是一个成员函数,需要this正常工作(除非你让静态的,当然)。您可以使用std::bind或lambda函数,然后将其包装到std::function中。

void Foo::create() 
{ 
    std::function<void()> fx1 = [this](){ callback(); }; 
    std::function<void()> fx2 = std::bind(&Foo::callback, this); 
    //mBars.push_back({ 1224, 26, callback }); //ERROR! 
    mBars.emplace_back(Bar{ 1224, 26, fx1 }); //ok 
    mBars.emplace_back(Bar{ 1224, 26, fx2 }); //ok 
} 
+0

谢谢凯文。这正是我需要的:) – waas1919