std::bind
如果你有 C++11,你可以使用。考虑以下示例,该示例通过在一次快速移动中将每个元素添加 5 来转换向量:
#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"
}
至于你的例子,我可以像这样写一些接近它的东西:
#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));
}
输出:
2.2 4.4 6.6 8.8 11
不过,我可能把事情复杂化了。这实际上是我第一次同时使用std::bind
和std::function
。