c++ function with callback code example

Example 1: c++ callback member function

class Foo {
	int (*func)(int);
  
public:
  	void setCallback( int (*cFunc)(int) ) {
      func = cFunc;
    }
  
  	void set() {
    	setCallback(callback);	// Set callback function to be called later
    }
  
    void use() {
      	func(5);	// Call the previously set callback function
    }
          
  	// Note the 'static'
    static int callback(int param) {
      	return 1;
    }
};

Example 2: c++ callback function

// C++ callback function

class Base {
public:
  void doSomething() {
    using namespace std::placeholders;
    // std::placeholders::_1 is for the callback parameter
    // use _1 for 1 argument
    // or _1, _2, _3 for 3 arguments and so on
    something.setCallback(std::bind(&Base::callback, this, _1));
    // std::bind is needed, otherwise 
    // the callback function would need to be static
  }
  
  // Callback function
  void callback(int i) {
    std::cout << "Callback: " << i << std::endl;
  }
}

Tags:

C Example