Search code examples
c++function-pointersglutstatic-functions

Can functions accept static function pointers as arguments?


Here's a good example: I'm trying to overload OpenGL's glutMouseFunc so it may accept the namespace, and class function of my choosing. The one in particular is Init::DisplayInit::mouse, which is static. The question is, is this possible? If so, how is this achieved?

My Implementation

void glutMouseFunc(void (Init::DisplayInit::*mouse)(int, int, int, int)) {
    (*mouse);
}

Errors from Implementation

..\OpenGL_03\/displayinit.h:27: error: variable or field 'glutMouseFunc' declared void
..\OpenGL_03\/displayinit.h:27: error: expected primary-expression before 'int'
..\OpenGL_03\/displayinit.h:27: error: expected primary-expression before 'int'
..\OpenGL_03\/displayinit.h:27: error: expected primary-expression before 'int'
..\OpenGL_03\/displayinit.h:27: error: expected primary-expression before 'int'
..\OpenGL_03\/displayinit.h:27: error: void value not ignored as it ought to be

Note, I put the declaration of the function in the same file's header file. I also made sure both the declaration and the definition of the function resided outside of the namespace declaration (which wraps most of both files, each). As shown, one of the first errors reads the function as a variable or field (???).


Solution

  • That's not a reasonable way to define glutMouseFunc. It isn't supposed to call the callback immediately, it's supposed to save a pointer for later (when mouse activity occurs).

    Call the GLUT-provided version, and pass the address of your function:

    #include <GL/glut.h>
    glutMouseFunc(&Init::DisplayInit::mouse);
    

    Static member functions are compatible with ordinary function pointers.