Welcome to our deep dive into C++'s std::function! This powerful tool is part of the C++11 standard library, making it easier to work with functions as first-class citizens. Let's explore what std::function is, why you might need it, and how to use it in practice.
std::function? šstd::function is a template class that can hold any callable object such as functions, functors, lambdas, and bind expressions. It acts as a polymorphic function object, allowing you to store and invoke functions at runtime.
std::function? š”std::function enables you to treat different functions as the same type, making it easier to write generic code.std::function with any function signature, making it versatile and reusable in various contexts.Let's create a simple example to demonstrate how to use std::function:
#include <iostream>
#include <functional>
void print(const std::string& message) {
std::cout << message << std::endl;
}
int main() {
// Create an std::function object holding the print function
std::function<void(const std::string&)> myFunction = print;
// Invoke the function through the std::function object
myFunction("Hello, World!");
return 0;
}Here's an example where we create a simple functor and use std::function to store and invoke it:
#include <iostream>
#include <functional>
#include <vector>
struct Square {
int operator()(int number) {
return number * number;
}
};
int main() {
std::vector<std::function<int(int)>> numbers;
// Add our Square functor to the vector
numbers.push_back(Square());
// Invoke the functor through the std::function
for (const auto& func : numbers) {
std::cout << func(5) << std::endl;
}
return 0;
}This example demonstrates a variadic template function that takes a variable number of arguments and returns the sum using std::function:
#include <iostream>
#include <functional>
#include <cstdarg>
template<typename... Args>
auto sum(Args... args) {
std::function<int()> sumFunction = [=]() {
int total = 0;
((total += args), ...);
return total;
};
return sumFunction();
}
int main() {
std::cout << sum(1, 2, 3, 4, 5) << std::endl;
return 0;
}What is `std::function` in C++?
Why use `std::function`?