====== C - C++ Callback functions ======
===== callback_function.hpp =====
#pragma once
#include
// 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
#include
#include
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 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 =====
https://en.cppreference.com/w/cpp/utility/functional/function