std::bind
It is library function and it is used to bind the set of parameters to the function and return the function object, using returned function object we can call the function. Example:
auto f = std::bind(add,1,2,std::placeholders::_1);//bind function //add => this is actual function //1, 2 => are available parameters //std::placeholders::_1 => It is placeholder(remaining parameter), this parameter is not present //int third = 5 => This is remaining parameter, now it is available and we can call the function f(third);//f(third) => Invoking add function with parameter(1,2,5)
When will we use it (What is the Objective/purpose of std::bind):
- When we want to pass the function logic as argument to algorithm (std::bind returns the function pointer, we can pass this to algorithm ).
- When we don’t have all parameters (we will get at run time) so we can bind the function with available parameters using std::bind and we can complete the call after getting remaining parameter(es).
Advantage /Important points:
- We may not always be able to get all the parameters of a function at one time so we can bind function with available parameters and we can complete the call when remaining parameter is available.
- Some time we don’t known the return type then using auto we can mitigate this problem.
- std::bind always binds the parameter with function by “pass by value”.
- If we wants to pass the parameter “pass by reference” then we need to add std::ref or std::cref.
Header file:
#include<functional>
source code with example:
/* Program: std::bind Author: Alpha Master Date: 27 Feb 2021 */ //Header File #include<iostream> #include<functional> //Function takes 3 parameters int add(int a, int b, int c) { return(a+b+c); } int main() { std::cout<<"std::bind"<<std::endl; //std::bind, it uses to bind the parameter(es) to function auto f = std::bind(add,1,2,std::placeholders::_1); std::cout<<"Enter the third parameter"<<std::endl; int third = 0; std::cin>> third; //invoke function pointer returned by bind std::cout<<"Result:"<<f(third)<<std::endl; return 0; }
Output:
std::bind Enter the third parameter 6 Result:9