Wednesday, November 4, 2015

Function Pointers in C/C++



#include <iostream>
#include <cstring>
#include <vector>

using namespace std;
namespace DemoFunPt {
typedef void (*CallBackFunc)(int i_input);
// Register callback function
vector<CallBackFunc> Callbackfuncs;

void Func_A(int i_input)
{
  cout<< "Hello from Func_A " << i_input << endl;
}

void Func_B(int i_input)
{
  cout<< "Hello from Func_B " << i_input << endl;
}

void RegisterCallbackFunc(CallBackFunc i_FuncPt)
{
  Callbackfuncs.push_back(i_FuncPt);
}

}

int  main()
{
   DemoFunPt::RegisterCallbackFunc(DemoFunPt::Func_A);
   DemoFunPt::RegisterCallbackFunc(DemoFunPt::Func_B);

   for(int i=0; i< DemoFunPt::Callbackfuncs.size(); i++){
      DemoFunPt::Callbackfuncs[i](i);
   }
   cout<<"Done demo" << endl;
   return 0;
}



root@trac ~# g++ funcpointer.cpp -o test
root@trac ~# ./test
Hello from Func_A 0
Hello from Func_B 1
Done demo

No comments: