std::bind and std::function
Programmers can use this pair of utilities to create and bind functions to variables.
We'll cover the following...
The two functions std::bind
and std::function
fit very well together. While std::bind
enables us to create new function objects on the fly, std::function
takes these temporary function objects and binds them to a variable. Both functions are powerful tools from functional programming and need the header <functional>
.
Let’s consider the example here:
Press + to interact
#include <algorithm>#include <functional>#include <iostream>#include <numeric>#include <vector>int main(){std::cout << std::endl;std::vector<int> myVec(20);std::iota(myVec.begin(), myVec.end(), 0);std::cout << "myVec: ";for (auto i: myVec) std::cout << i << " ";std::cout << std::endl;std::function< bool(int)> myBindPred= std::bind( std::logical_and<bool>(),std::bind( std::greater <int>(), std::placeholders::_1, 9 ), std::bind( std::less <int>(), std::placeholders::_1, 16 ));myVec.erase(std::remove_if(myVec.begin(), myVec.end(), myBindPred), myVec.end());std::cout << "myVec: ";for (auto i: myVec) std::cout << i << " ";std::cout << std::endl;}
🔑 std::bind and std::function are mostly superfluous
std::bind
andstd::function
, which were part of TR1, are mostly unnecessary with C++11. Instead, we can use lambda functions instead ofstd::bind
and most often can use the ...