0

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
0

1 Answer 1

2

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); };
Sign up to request clarification or add additional context in comments.

4 Comments

Yikes, I'm not keeping up with c++ syntactic sugar, but it looks like Perl devotees have taken over the ANSI steering committee!
I'd recommend using &MyWindow::memberFunction instead of &this->memberFunction for emphasizing that member function body is the one for all objects and has the same address. Moreover I'm not sure &this->memberFunction is valid at all
Using default capture by copy to only capture this seems a bit strange. As I understand it, that behavior will be deprecated in c++20 according to cppreference.
@super True - habit. Perhaps [this] would have been better. FWIW I never found it strange - this is indeed (or should be) captured by copy (though *this wouldn't be)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.