Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding std::function in C++

Tech May 13 1

std::function is a template class introduced in C++11 that serves as a general-purpose wrapper for callable entities. It allows you to store, copy, and invoke a variety of callable objects using a uniform interface.

Callable objects in C++ include:

  • Free functions
  • Lambda expressions
  • Function objects (functors)
  • Member functions
  • Other callable types

Here are examples of different callable types:

// Free function
int multiply(int x) {
    return x * 2;
}

// Lambda expression
auto square = [](int n) { return n * n; };

// Functor
struct Adder {
    int increment;
    Adder(int inc) : increment(inc) {}
    int operator()(int value) {
        return value + increment;
    }
};

std::function provides a consistent way to handle these diverse callable types:

#include <functional>
#include <iostream>

int main() {
    std::function<int(int)> executor;
    
    // Assign free function
    executor = multiply;
    std::cout << "Free function: " << executor(5) << std::endl;
    
    // Assign lambda
    executor = square;
    std::cout << "Lambda: " << executor(5) << std::endl;
    
    // Assign functor
    Adder addFive(5);
    executor = addFive;
    std::cout << "Functor: " << executor(10) << std::endl;
    
    return 0;
}

The key advantage of std::function is that it abstracts away the specific type of callable object, allowing you to write more flexible and reusable code. You can store different callable types in the same std::function variable and invoke them using identical syntax.

std::function is particularly useful in scenarios where you need to pass callbacks, implement strategy patterns, or create event handling systems where the specific implementation may vary at runtime.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.