Right to the point:
I have a class (Button)
I want to make that button execute a non-static member function owned by another class (Game)
public:
template<class Class>
explicit Button(void (Class::*func)(), Class* T) {
//(T->*func)(); // OK
m_PressFunction = [&](){(T->*func)()};
m_PressFunction(); // OK
}
private:
std::function<void()> m_PressFunction{nullptr}; //STAYS NULLPTR?
Problem is: once the scope is left, m_PressFunction becomes nullptr.
How can I store it right?
UPD
Minimal, Complete, and Verifiable example as asked by @aschepler:
#include <functional>
#include <iostream>
class Button {
public:
explicit Button() {};
explicit Button(const Button& other) { m_PressFunction = other.m_PressFunction; };
explicit Button(Button&& other) { m_PressFunction = other.m_PressFunction; };
Button& Button::operator=(const Button& other) { m_PressFunction = other.m_PressFunction; return *this; };
Button& operator=(Button&& other) { m_PressFunction = other.m_PressFunction; return *this; };
~Button() {};
template<class Class>
explicit Button(void (Class::*func)(), Class& T) {
m_PressFunction = [&]() {(T.*func)(); };
m_PressFunction(); // OK
}
void runPressFunction() { if (m_PressFunction != nullptr) { m_PressFunction(); } else std::cout << "Tried to run nullptr m_PressFunction. IT DOES NOT WORK\n"; };
private:
std::function<void()> m_PressFunction{ nullptr }; //STAYS NULLPTR?
};
class Game {
public:
Game::Game() { m_Button = Button(&Game::PressFunction, *this); };
void runButtonFunction() { m_Button.runPressFunction(); };
private:
void PressFunction() { std::cout << "Game::PressFunction() called. IT WORKS\n"; };
Button m_Button;
};
int main() {
Game game;
game.runButtonFunction();
std::cin.get();
}
Well, it's not null anymore (my bad for forgetting to put m_PressFunction into rule of 5), but it's still not working. Any hints?