// funtors.cpp : Defines the entry point for the console application. // #include "stdafx.h" typedef float (*MyFuncPtrType)(int, char *); MyFuncPtrType my_func_ptr; float test_func(int a, char *c) { fprintf(stderr, "in a function with argument: %d, %s\n", a, c); fflush(stderr); return a + 10.123f; } class functors; typedef float (functors::*ClassMemFuncPtr)(int, char *); // For const member functions, it's declared like this: typedef float (functors::*ClassConstMemFuncPtr)(int, char *) const; class functors { public: virtual ~functors() { obj = 0; } void invoke() { (obj->*memx)(10, "Yeah!!"); } void bind_x(MyFuncPtrType funcPtr) { x = funcPtr; } float invoke_x(int a, char* c) { return x(a, c); } void bind_memx(functors *obj, ClassMemFuncPtr mem_func) { this->obj = obj; memx = mem_func; } float invoke_memx() { return (obj->*memx)(11, "Uh yeahh.. i'm invoked!!"); } private: MyFuncPtrType x; ClassMemFuncPtr memx; functors *obj; }; class derived: public functors { public: float derived_func(int a, char *c) { fprintf(stderr, "I got called with the following params: %d, %s", a, c); return 1.01111f; } }; int _tmain(int argc, _TCHAR* argv[]) { my_func_ptr = test_func; float a = my_func_ptr(10, "yohan"); fprintf(stderr, "%f\n", a); fflush(stderr); functors *base = new functors(); base->bind_x(test_func); a = base->invoke_x(11, "pandewi"); fprintf(stderr, "%f\n", a); fflush(stderr); //testing member function.. derived *the_derived = new derived(); base->bind_memx(the_derived, static_cast(&derived::derived_func)); base->invoke_memx(); delete the_derived; base->invoke_memx(); delete base; return 0; }
Jumat, 02 November 2012
[c++] Function Pointers Snippet
Hi there, let the code speaks for it self.. ;)
Langganan:
Posting Komentar (Atom)
Tidak ada komentar:
Posting Komentar