如果您有C++ 11,則可以使用std::bind
。下面這個例子,通過動作迅速地將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
。
查看'std :: bind'。您可以將值綁定到函數中的一個或多個參數。 – chris
非常感謝,我會檢查一下。 – vanna
如果你沒有支持'std :: function'和'std :: bind'的C++ 11支持,並且在''中找到佔位符,那麼你可以使用Boost等價物。 –
AJG85