Binders make up part of functional composition that allows you to adapt functions and combine them into new functions.
Let’s say you have a method that multiplies two numbers. Actually, you already have one. It comes with the standard C++ library and it’s one of the predefined function objects. You have many predefined function objects to add, subtract, multiple, divide, compare for equality, compare for less than or greater than, and many more. You might wonder why you would need function objects for this when you can instead just use the operators. Sometimes you need to pass these operations to some other code to run and that expects either a function pointer, a function object, or a lambda. And it’s much easier to use one of the predefined function objects.
You have a function object that multiplies two numbers and you’d like to use that to send to a collection to multiply each number in the collection by two. Why would you want to do that? Well, maybe you need to temporarily speed up a game character’s capabilities. The collection will allow you to pass it a function object that takes a single parameter. It uses that parameter to pass one of the numbers from the collection and calls the function once for each number in the collection.
You see the problem here? The collection wants to call a method and pass a single number argument. But the multiplies function object needs two numbers.
You know that one of those numbers is two. Or whatever value you need. You could write your own function that multiples a single argument by two. Or you could write your own function object that allows you to specify what value to use when multiplying. Or you could use a lambda and capture the value to be used to multiply each number. But you can’t use the predefined multiplies function object as-is.
In addition to all of the predefined function objects, you have function adapters and together they make up something called functional composition. This allows you to build a composite function out of smaller functions. Just like what the composite design pattern describes. Listen to episode 66 for more information about the composite design pattern.
The bind adapter takes an operation as its first parameter and then allows you to pass in other arguments as needed. Some of these arguments could be specific values such as the number two we need in order to multiply each number in a collection by two. The operation in this case is the multiplies function object. Whatever argument you pass for the operation of bind will need a certain number of arguments itself. That’s why bind allows you to pass in however many arguments you need. These arguments will be used to call the operation.