Last active
August 29, 2015 14:14
-
-
Save mihids/64588b533063e412b9c0 to your computer and use it in GitHub Desktop.
Using function pointers for C++ class member function callbacks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdlib> | |
#include <iostream> | |
class A { | |
public: | |
int callback(float variable) { | |
int result =6; | |
std::cout << "Callback invoked with result: " << result + variable << std::endl; | |
return result; | |
} | |
}; | |
typedef int (A::*CallbackType)(float); // means CallbackType is a type definition for any function in A with a float argument | |
//and a return type of int | |
void DoWorkObject(CallbackType callback) { | |
//Class instance to invoke it through | |
A objectInstance; | |
//Invocation | |
int result = (objectInstance.*callback)(1.0f); | |
} | |
//This method performs work using an object pointer | |
void DoWorkPointer(CallbackType callback) { | |
//Class pointer to invoke it through | |
A * pointerInstance; | |
//Invocation | |
int result = (pointerInstance->*callback)(1.0f); | |
} | |
int main() { | |
DoWorkObject(&A::callback); | |
DoWorkPointer(&A::callback); | |
// These functions are regiistered with callback functions. | |
// When they are done they can notify by calling these callbacks | |
// i.e. callback is similar to OnMouseClieck and DoWorkObject/DoWorkPointer are smiliar to actual events | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment