How do I use function pointers and std::function?

In C++, function pointers and `std::function` are powerful tools that allow you to store and invoke functions dynamically. Function pointers are a way to point to functions, while `std::function` provides a more flexible and type-safe way to encapsulate callable entities.

Function Pointers

A function pointer can point to a function of a specific signature. This allows you to call different functions dynamically depending on certain conditions.

Using std::function

`std::function` is a part of the C++ Standard Library that can store any callable target, such as functions, lambda expressions, or bind expressions. It provides a convenient way to handle callbacks.

Example

#include <iostream> #include <functional> // Function to be used void printMessage(const std::string &message) { std::cout << "Message: " << message << std::endl; } int main() { // Using function pointer void (*funcPtr)(const std::string &) = printMessage; funcPtr("Hello from function pointer!"); // Using std::function std::function funcObj = printMessage; funcObj("Hello from std::function!"); return 0; }

function pointers std::function C++ callbacks dynamic function calls C++ programming