带有指向函数的指针的 C++ 向量 push_back

waa*_*919 1 c++ function-pointers vector std-function

我有一类Foo含有vectorBarS:

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

    std::vector<Bar> mBars;
}
Run Code Online (Sandbox Code Playgroud)

我的Bar类包含这个构造函数:

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

我的Foo班级有一个create()Bars添加到mBars向量的方法:

void Foo::create()
{
    mBars.push_back({ 1224, 26, callback }); //ERROR!
}
Run Code Online (Sandbox Code Playgroud)

如何设置函数指针,使用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    
Run Code Online (Sandbox Code Playgroud)

小智 5

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
}
Run Code Online (Sandbox Code Playgroud)