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

时间:2017-07-09 19:22:37

标签: c++ vector function-pointers std-function

我有一个班级Foo,其中包含vectorBar

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添加到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 个答案:

答案 0 :(得分: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
}
相关问题