How to write callbacks in C++

A simple guide to writing function callbacks in C++.

For the C# equivalent of using delegate see this link:

https://www.technical-recipes.com/2016/how-to-use-delegates-in-c

The steps you need to take are:

1. Declare the function pointer that will be used to point to functions of given return types/argument(s)

In this example a pointer to function that takes and int and returns an int:

typedef int(*fptr)(int);

2. Create the example functions that will be pointed to by the function pointer

In these examples they functions that will be used to transform your number:

int DoubleValue(int value)
{
   return value * 2;
}

int SquareValue(int value)
{
   return value * Value;
}

3. Apply the callback usage

In this case write a function that accepts that the function pointer as well as the argument(s) used by that function pointer:

int TransformValue(int value, fptr f)
{
   return f(value);
}

Full Code Listing showing example usage:

#include <iostream>

typedef int(*fptr)(int);

int DoubleValue(int value)
{
   return value * 2;
}

int SquareValue(int value)
{
   return value * value;
}

int TransformValue(int value, fptr f)
{
   return f(value);
}

int main()
{
   const int value = 10;

   std::cout << "Value doubled = " << TransformValue(value, DoubleValue) << std::endl;
   std::cout << "Value squared = " << TransformValue(value, SquareValue) << std::endl;

   return 0;
}

Giving the following output as follows:

callbacks

`