Simple Callback Function In C++

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 CustomClass and int
  • The function should return int
  • Such function type could be referred using the denotation CbFunc inside CustomClass

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.

Published by Oyasumi

Just a normal person in the world

Leave a Reply

Your email address will not be published. Required fields are marked *