Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
std::function in C++
Next article icon

std::function in C++

Last Updated : 22 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The std::function() in C++ is a function wrapper class which can store and call any function or a callable object. In this article, we will learn about std::function in C++ and how to use it in different cases.

Table of Content

  • What is std::function in C++?
  • Example of std::function
  • Member Functions of std::function
  • Applications of std::functions in C++
  • More Examples of std::function
  • std::function in C++ - FAQs

What is std::function in C++?

std::function is a template class in C++ that is used to wrap a particular function or any other callable object such as a lambda, or function object. It is generally used to write generic code where we need to pass functions as arguments in another function (callbacks). It avoids the creation of extra overloads of the function that may take similar callback functions as arguments.

std::function is defined in the <functional> header file.

Declaration

To create a wrapper object, we first declare it using the following syntax:

std::function< rtype (atype...)> name();

where,

  • name: Name of the wrapper.
  • atype: Types of the arguments that function takes.
  • rtype: Return type of the function you want to store.

Initialization

The above syntax only creates an empty instance of std::function. To wrap a particular function inside this wrapper object, we use assignment operator as shown:

std::function< ret_t (args_t)> name = f;

where f is the function to be wrapped.

We can also initialize it at the time of declaration:

std::function< ret_t (args_t)> name(f);

Example of std::function

C++
// C++ Program to illustrate the working // std::function #include <bits/stdc++.h> using namespace std;  int f(int a, int b) {   return a + b; }  int main() {      	// std::function wrapping traditional   	// function 	function<int(int, int)> calc = f;   	cout << "Sum: " << calc(8, 2) << endl;        	// std::function wrapping a lambda     // expression     calc = [](int a, int b) { return a * b; };   	cout << "Product: " << calc(8, 2);     return 0; } 

Output
Sum: 10 Product: 16 

Member Functions of std::function

std::function contains some member functions to provide some basic functionality. The following table lists some useful member functions of std::function class template:

Function

Description

swap()

Swaps the wrapped callable of two std::function objects.

operator bool

Checks if the std::function contains a callable.

operator ()

Invoke the callable with the given arguments.

target()

Returns a pointer to the stored callable. If there is no callable stored, returns nullptr.

target_type()

Returns the typeid of the callable. If no callable is stored, it returns typeid(void).

Applications of std::functions in C++

Apart from the applications shown in the above examples, std::function can also be used for:

  • Callbacks: Used for event-driven systems where functions are passed and called later when an event occurs.
  • Function Wrapping and Higher-Order Functions: Allows passing functions as parameters and returning them.
  • Stateful Callbacks: Enables callbacks with preserved states, making it easier to manage state without global variables.
  • Replacing Function Pointers: Provides a safer and more flexible alternative to traditional function pointers, supporting multiple callable types.

More Examples of std::function

The following examples demonstrates the usage of std::function in C++ for different applications such as callbacks, state preserved callbacks, function composition.

Example 1: Passing std::function as Argument (Callback)

C++
// C++ program to pass the std::function // as arguments #include <bits/stdc++.h> using namespace std;  // Functions for simple math operations int add(int a, int b) {     return a + b; } int sub(int a, int b) {     return a - b; } int mul(int a, int b) {     return a * b; } int divs(int a, int b) {     return a / b; }  // Using std::function as parameter void func(int a, int b,           function<int(int, int)> calc) {        int res = calc(a, b);     cout << "Result: " << res << endl; }  int main() {        	// Calling all the arithmetic functions     func(8, 2, add);     func(8, 2, sub);     func(8, 2, mul);     func(8, 2, divs);     return 0; } 

Output
Result: 10 Result: 6 Result: 16 Result: 4 

Example 2: Wrapping Member Functions of a Class

We can also wrap a member function of a class using std::function object but we have to add one extra argument as shown in the below program.

C++
// C++ program to demonstrate usage of // unction with member functions #include <bits/stdc++.h> using namespace std;  class C { public:     int f(int a, int b) {         return a * b;     } };  int main() {     C c;          // Wrapping member function of C     function<int(C&, int, int)> calc = &C::f;          // Call the member function using function   	if (calc)     	cout << "Product: " << calc(c, 4, 5);   	else       	cout << "No Callable Assigned";     return 0; } 

Output
Product: 20

Example 3: Composing Two Functions into One

C++
// C++ program to demonstrate usage of // std::function for function composition #include <bits/stdc++.h> using namespace std;  // Composed function function<int(int)> cf(function<int(int)> f1,                         function<int(int)> f2) {      	// Returning a lambda expression that   	// in turn returns a function     return [f1, f2](int x) {              	// Apply f1 first, then f2         return f2(f1(x));      }; }  int main() {     auto add = [](int x) { return x + 2; };     auto mul = [](int x) { return x * 3; };      function<int(int)> calc = cf(add, mul);     cout << calc(4);     return 0; } 

Output
18

Explanation: In this example, we composted two lambda functions add() and mul() into one function cf() which takes two function wrappers and returns another function wrapper. Then we created a wrapper for this using this composed function and use it to perform the addition and multiplication operator at one call.


Next Article
std::function in C++

A

anmolpanxq
Improve
Article Tags :
  • C++
  • CPP-Functions
  • cpp-advanced
  • cpp-memory-management
Practice Tags :
  • CPP

Similar Reads

    Functions in C++
    A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
    9 min read
    log() Function in C++
    The std::log() in C++ is a built-in function that is used to calculate the natural logarithm (base e) of a given number. The number can be of any data type i.e. int, double, float, long long. It is defined inside the <cmath> header file.In this article we will learn about how to use std::log()
    1 min read
    Function Pointer in C++
    Prerequisites: Pointers in C++Function in C++ Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of point
    4 min read
    Function Pointer in C
    In C, a function pointer is a type of pointer that stores the address of a function, allowing functions to be passed as arguments and invoked dynamically. It is useful in techniques such as callback functions, event-driven programs, and polymorphism (a concept where a function or operator behaves di
    6 min read
    Virtual Function in C++
    A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object a
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences