std::bind
C++11をお持ちの場合にご利用いただけます。1回の素早い動きで各要素に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
。