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.
A function pointer can point to a function of a specific signature. This allows you to call different functions dynamically depending on certain conditions.
`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.
#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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?