Pointing to a function that is a class member - glfw setKeycallback

前端 未结 7 1237
遇见更好的自我
遇见更好的自我 2020-12-02 11:27

I\'m writing a glfw app, in which I\'ve wrapped the function callse into a simple class. Im having trouble setting the key callback. My class is defined as:

         


        
7条回答
  •  Happy的楠姐
    2020-12-02 11:52

    Inspired by N0vember's answer, I present you even more generic and dynamic solution:

    class MyGlWindow {
    public:
        std::function onClose;
        std::function onMouseClick = [](auto self, int, int, int) { /*some default behavior*/ };
    };
    
    void makeWindow() {
        GLFWwindow* glfwWindow;
        MyGlWindow* myWindow;
    
        /* ... Initialize everything here ... */
    
        glfwSetWindowUserPointer(glfwWindow, myWindow);
    
        #define genericCallback(functionName)\
            [](GLFWwindow* window, auto... args) {\
                auto pointer = static_cast(glfwGetWindowUserPointer(window));\
                if (pointer->functionName) pointer->functionName(pointer, args...);\
            }
    
        glfwSetWindowCloseCallback(glfwWindow, genericCallback(onClose));
        glfwSetMouseButtonCallback(glfwWindow, genericCallback(onMouseClick));
    
        myWindow->onMouseClick = [](auto self, int, int, int) {
            std::cout << "I'm such a rebel" << std::endl;
            self->onClose = [](auto self) {
                std::cout << "I'm such a rebellion" << std::endl;
            };
        };
    }
    

提交回复
热议问题