This article will discuss the basic practice of using callback functions in C++
Function Type
To use function type as parameter, it’s recommended to use functional library to define function type:
#include <functional>
class CustomClass
{
using CbFunc = std::function<int(CustomClass, int)>
}
In the code snippet above:
- We define a function that receive a two parameter with type
CustomClassandint - The function should return
int - Such function type could be referred using the denotation
CbFuncinsideCustomClass
Use With Lambda
It’s recommended to use Function Type with Lambda Expression:
CbFunc customCallbackFunction = [](instance, value){
// function body here
}
For more info about the C++ Lambda Expression, check out this blog post.