Bind Function and Placeholders in C++
Sometimes we need to manipulate the operation of a function according to the need, i.e changing some arguments to default, etc. Predefining a function to have default arguments restricts the versatility of a function and forces us to use the default arguments and that too with similar values each time. From C++11 onwards, the introduction of the bind function has made this task easier.
How does bind() work?
Bind function with the help of placeholders helps to manipulate the position and number of values to be used by the function and modifies the function according to the desired output.
What are placeholders?
Placeholders are namespaces that direct the position of a value in a function. They are represented by _1, _2, _3…
In the above code, bind() modified the call of a function to take 1 argument and returned the desired output.
Properties of Placeholders
1. The position of the placeholder determines the value position in the function call statement
The value of function is : 10 The value of function after changing placeholder position is : -14
In the above code, even though the position of 1 and 13 were the same in a function call, the change in the position of placeholders changed the way the function was called.
2. The number of placeholders determines the number of arguments required to pass in the function.
We can use any no. of placeholders in the function call statement (obviously less than the maximum number of arguments). The rest values are replaced by the user-defined default values.
The value of function with 1 placeholder is : 4 The value of function with 2 placeholders is : 10 The value of function with 3 placeholders is : 8
In the above code, clearly the no. of placeholders equated to the number of arguments required to call the function. The binding of function is directed by the number and position of placeholders.
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.