I'd like to store a function pointer to a private member function of my object inside my class. Basically I want to do this:
MyWindow::MyWindow()
{
std::function<void(int&)> func = this->memberFunction; // ERROR
}
void MyWindow::memberFunction(int& i)
{
// do something
}
When I try to build it the compiler throws an error:
Error C3867: 'MyWindow::memberFunction': non-standard syntax; use '&' to create a pointer to member
The error message for C3867 tells you the first problem: you need to use &
to form a function pointer.
Your next problem is that you do not have a function pointer, but a pointer-to- member -function, and that is not compatible with your std::function
, which is missing anywhere to store or pass the implicit first argument that holds the "this" pointer.
You can, however, "bind" a value for that argument, in effect hardcoding it into the functor.
You're also going to need to spell it MyWindow::memberFunction
rather than this->memberFunction
, because that's just the way it is (to quote GCC: "ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function").
So:
using std::placeholders;
std::function<void(int&)> func = std::bind(&MyWindow::memberFunction, this, _1);
Or, using modern techniques:
std::function<void(int&)> func = [this](int& x) { memberFunction(x); };
Or just:
auto func = [this](int& x) { memberFunction(x); };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.