std::function
It is function object with specific return type and a specific argument type and it is a generic, polymorphic function wrapper whose instances can store, copy, and call any target entity that can be called, in other word std::function can be used to store and call a function or function pointer or auto or return of lambda or return of bind().
In other word:
It is like “function pointer of C language“, we need to specify return type and parameter and then it will be used to call assigned function.
When will we use it (What is the Objective/purpose of std::function):
- If we want to assign the result of bind() or return of lambda to variable of specific type.
- When we want to pass the function logic as argument to algorithm (std::function is function object, we can pass this to algorithm ).
- std::function objects are useful for callback.
Header file:
#include<functional>
source code with example:
/* Program: std::function Author: Alpha Master Date: 28 Feb 2021 */ //Header File #include<iostream> #include<functional> int add(int a, int b) { return a+b;} int main() { std::cout<<"std::function"<<std::endl; //Assign a function std::function<int(int, int)>f1 = add; //Assign a lambda std::function<int(int, int)>f2 = [](int a, int b){ return (a+b);}; //Assign a bind call std::function<int(int)>f3 = std::bind(add, 1, std::placeholders::_1); //calling std::cout<<"f1:"<<f1(1,2)<<std::endl; std::cout<<"f2:"<<f2(1,2)<<std::endl; std::cout<<"f3:"<<f3(2)<<std::endl; return 0; }
Output:
std::function f1:3 f2:3 f3:3