Answers for "callback c++"

C++
1

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;
  }
}
Posted by: Guest on February-07-2021
2

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);
}
Posted by: Guest on May-05-2021

Browse Popular Code Answers by Language