C++ std::function (C++11) šŸŽÆ

beginner
11 min

C++ std::function (C++11) šŸŽÆ

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.

What is 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.

Why use std::function? šŸ’”

  • Function Polymorphism: std::function enables you to treat different functions as the same type, making it easier to write generic code.
  • Function Container: Store and invoke functions at runtime, simplifying callback implementations and event-driven programming.
  • Template Parameterized: Use std::function with any function signature, making it versatile and reusable in various contexts.

Basic Usage šŸ’”

Let's create a simple example to demonstrate how to use std::function:

cpp
#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; }

Advanced Examples šŸ’”

Functor Example

Here's an example where we create a simple functor and use std::function to store and invoke it:

cpp
#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; }

Variadic Template Function Example

This example demonstrates a variadic template function that takes a variable number of arguments and returns the sum using std::function:

cpp
#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; }

Quiz šŸ’”

Quick Quiz
Question 1 of 1

What is `std::function` in C++?

Quick Quiz
Question 1 of 1

Why use `std::function`?