关键点:
我有一个班级(按钮)
我想让该按钮执行另一个类所拥有的非静态成员函数(游戏)
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
@aschepler提出的Minimal, Complete, and Verifiable example:
#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的规则中),但它仍然不起作用。任何提示?
答案 0 :(得分:0)
最后修复。
PYTHONPATH