callback function c++ code example

Example 1: callback c++ c

//Define a type for the callback signature,
//it is not necessary, but makes life easier

//Function pointer called CallbackType that takes a float
//and returns an int
typedef int (*CallbackType)(float);  


void DoWork(CallbackType callback)
{
  float variable = 0.0f;

  //Do calculations

  //Call the callback with the variable, and retrieve the
  //result
  int result = callback(variable);

  //Do something with the result
}

int SomeCallback(float variable)
{
  int result;

  //Interpret variable

  return result;
}

int main(int argc, char ** argv)
{
  //Pass in SomeCallback to the DoWork
  DoWork(&SomeCallback);
}

Example 2: 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 3: 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