正确一点:
我有一堂课(按钮)
我想让该按钮执行另一个类(游戏)拥有的非静态成员函数
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?
问题是:一旦保留作用域,m_PressFunction就会变为nullptr。
如何正确存储?
UPD
Minimal, Complete, and Verifiable example,如@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();
}
好吧,它不再是null(我很遗憾忘记将m_PressFunction设置为5的规则),但是它仍然无法正常工作。有什么提示吗?
最佳答案
终于解决了。
template<class Class>
explicit Button(void (Class::*func)(), Class* const T) {
m_PressFunction = [T, func]() {(T->*func)(); };
}