Registering callback using std::function in C++


Welcome to the next pikoTutorial!

Imagine you’re building an application that processes some data and once it’s done, the user needs to be notified about the result. Since you don’t want to hard-code the notification logic, it’s better to allow the user to register a custom function that will be called automatically after the data processing completes.

Using std::function for callback registration

One of the most flexible ways to implement callbacks in C++ is by using std::function. std::function can store and invoke any callable object (functions, lambdas, or function objects) that matches a specific signature. The overall syntax is:

std::function<function_return_type(function_argument_types)> name;

Let’s define a ProcessData unction that accepts a callback and notifies the user once processing is complete.

#include <iostream>
#include <functional>
// Type alias for the callback type
using CallbackType = std::function<void(const bool)>;
// Function accepting callback as an argument
void ProcessData(const CallbackType& callback) {
    // Simulate data processing
    std::cout << "Processing data" << std::endl;
    // Notify user via callback
    callback(true);
}
// Callback function definition
void Callback(const bool result) {
    std::cout << "Callback called! Result: " << result << std::endl;
}

int main() {
    // Register a callback using an existing function
    ProcessData(Callback);
    // Register a callback using lambda function
    ProcessData([](const bool result) {
        std::cout << "Lambda called! Result: " << result << std::endl;
    });
    // Register using callable object
    CallbackType cb = [](const bool result){
        std::cout << "Callable called! Result: " << result << std::endl;
    };
    ProcessData(cb);
}