You can use std::bind if you have C++11. Consider this example that transforms a vector by adding 5 to each element in one swift movement:
#include <iostream>
using std::cout;
#include <functional>
using std::plus;
using std::bind;
using std::placeholders::_1;
#include <vector>
using std::vector;
#include <algorithm>
using std::transform;
int main()
{
vector<int> v {1, 3, 6};
//here we bind the value 5 to the first argument of std::plus<int>()
transform (v.begin(), v.end(), v.begin(), bind (plus<int>(), _1, 5));
for (int i : v)
cout << i << ' '; //outputs "6 8 11"
}
As for your example, I was able to write something close to it like this:
#include <iostream>
using std::cout;
#include <functional>
using std::bind;
using std::function;
using std::placeholders::_1;
void foo (function<double (double, double)> func) //take function object
{
//try to multiply by 3, but will do 2 instead
for (double i = 1.1; i < 5.6; i += 1.1)
cout << func (i, 3) << ' ';
}
double bar (double x, double y)
{
return x * y;
}
int main()
{
foo (bind (bar, _1, 2));
}
Output:
2.2 4.4 6.6 8.8 11
I might have overcomplicated something though. It was actually my first time using both std::bind and std::function.
std::bind. You can bind a value to one or more arguments in a function.std::functionandstd::bindwith placeholders found in<functional>then you can use the Boost equivalents.