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 value each time. From C++11 onwards, the introduction of 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 namespace which 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 placeholder determines the value position in 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 same in function call, the change in position of placeholders changed the way function was called.
2. The number of placeholders determine the number of arguments required to pass in function
We can use any no. of placeholders in 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 the number of arguments required to call the function. The binding of function is directed by 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 contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- How to bind to port number less than 1024 with non root access?
- Function Overloading vs Function Overriding in C++
- What happens when a virtual function is called inside a non-virtual function in C++
- fma() function in C++
- div() function in C++
- arc function in C
- exp() function C++
- log() function in C++
- wcspbrk() function in C/C++
- exp2() function in C++ STL
- fread() function in C++
- feupdateenv() function in C++
- strtol() function in C++ STL
- raise() function in C++
- wcstombs() function in C++ STL