waas1919
waas1919

Reputation: 2595

C++ vector push_back with pointer to function

I have a class Foo which contains a vector of Bars:

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

    std::vector<Bar> mBars;
}

My Bar class contains this constructor:

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

My Foo class has a create() method that adds Bars to the mBars vector:

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

How can I set the function pointer, using std::function? and also without creating a separate object and push_back into the vector? Like the line above, where I get the error:

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

Upvotes: 1

Views: 1724

Answers (1)

Kelvin Sherlock
Kelvin Sherlock

Reputation: 853

callback is a member function and needs this to work correctly (unless you make it static, of course). You can use std::bind or a lambda function and then wrap it into a 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
}

Upvotes: 5

Related Questions