/* printf example */ #include #if 0 class MyClass { public: // This is our application callback handler for when a message is received, we will // pass this into the library which deals with message parsing void onMsg(int num1, int num2) { printf("onMsg() called with num1=%i, num2=%i\n", num1, num2); } }; class LibraryClass { public: // For the library class to call the onMsg, it has to be passed both an instance // of MyClass and a pointer to the member function to call // Note that MyClass has to be known here! This creates undesired coupling...in // reality your library should never have to know about MyClass void passACallbackToMe(void (MyClass::* onMsg)(int num1, int num2)) { // Call the callback function (onMsg)(1, 2); } }; void onMsg(int num1, int num2) { printf("onMsg() called with num1=%i, num2=%i\n", num1, num2); } int main() { MyClass myClass; LibraryClass libraryClass; // Provide the instance and function to call libraryClass.passACallbackToMe(&myClass, &MyClass::onMsg); libraryClass.passACallbackToMe((onMsg)(1,2)); } #else #include void globalfunction(int i) { printf("Global (%i)\n", i); } static void staticglobalfunction(int i) { printf("Static Global (%i)\n", i); } namespace Name_Space { void namespacefunc(int i) { printf("Namespace (%i)\n", i); } } void (*returnfunction(const char* str))(int) { printf("Return \"%s\":\n", str); return &globalfunction; } typedef void (*functiontype)(int); class Test { public: void (*funcptr1)(int i); void (Test::* funcptr2)(int i); void classfunction(int i) { printf("Class (%i)\n", i); } static void staticclassfunction(int i) { printf("Static Class (%i)\n", i); } void callglobal(int i) { funcptr1 = &globalfunction; (*funcptr1)(i); } void callclass(int i) { funcptr2 = &Test::classfunction; (this->*funcptr2)(i); } }; int main() { Test test; // Global function with local function-pointer void (*funcptr1)(int i) = &globalfunction; (*funcptr1)(1); // Static global function with local function-pointer void (*funcptr2)(int i) = &staticglobalfunction; (*funcptr2)(2); // Function in namespace with local function pointer void (*funcptr3)(int i) = &Name_Space::namespacefunc; (*funcptr3)(3); // Static member function with local function pointer void (*funcptr4)(int i) = &Test::staticclassfunction; (*funcptr4)(4); // Global function with class-function-ptr inside class test.callglobal(5); // Global function with class-function-ptr outside class test.funcptr1 = &globalfunction; (*test.funcptr1)(6); // Class function with class-function-ptr inside class test.callclass(7); // Class function with local function-ptr void (Test:: * classfunc)(int i) = &Test::classfunction; (test.*classfunc)(8); // Class function with class-function-ptr outside class test.funcptr2 = &Test::classfunction; (test.*(test.funcptr2))(9); (*returnfunction("global"))(10); printf("Using typedef:\n"); functiontype typefuncptr = &globalfunction; (*typefuncptr)(11); return 0; } #endif