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: [code language="cpp"] typedef int(*fptr)(int); [/code] 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: [code language="cpp"] int DoubleValue(int value) { return value * 2; } int SquareValue(int value) { return value * Value; } [/code] 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: [code language="cpp"] int TransformValue(int value, fptr f) { return f(value); } [/code] Full Code Listing showing example usage: [code language="cpp"] #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; } [/code] Giving the following output as follows: callbacks

Comments

Popular posts from this blog

Using the Supervisor Controller Pattern to access View controls in MVVM

Getting started with client-server applications in C++

How to send an e-mail via Google SMTP using C#