Reputation: 2595
I have a class Foo
which contains a vector
of Bar
s:
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 Bar
s 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
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