User Tools

Site Tools


c:c_callback_functions

C - C++ Callback functions

callback_function.hpp

#pragma once
 
#include <string>
 
// Define a callback function based on a class method and call it with argument "output".
void use_callback_function(std::string output);

callback_function.cpp

#include "callback_function.hpp"
#include <string>
#include <iostream>
#include <functional>
 
 
class MyClass
{
public:
  static void mystaticfunction(std::string str)
  {
    std::cout << str << std::endl;
  }
 
 
  void mymemberfunction(std::string str)
  {
    mystaticfunction(str);
  }
};
 
 
void test(std::string str, std::function<void(std::string)> callBack = nullptr)
{
  if (callBack)
  {
    callBack(str);
  }
}
 
 
void use_callback_function(std::string output)
{
  // Sample 1.
  test(output, MyClass::mystaticfunction);
 
 
  // Sample 2.
  MyClass myClass;
  auto callBack = [&myClass](std::string str)
  {
    myClass.mymemberfunction(str);
  };
 
  test(output, callBack);
}

References

c/c_callback_functions.txt · Last modified: 2021/04/28 08:34 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki