我有一个有两个参数的函数,我想将第二个参数绑定(bind)到一个值并获得一个新的函数对象。
我想要的在c++11中std::bind已经完美支持,例如:
int my_func(int a, int b) {...}
auto bind_func = std::bind (my_func,_1, 555);
或者在 python 中:
bind_func = functools.partial(my_func, b=555)
但我想在 C++03 中完成,我知道 boost 可以做到,但我不想为这个简单的要求调用 boost。
现在我写了自己的模板来做,但如果我能使用标准库就完美了。
有人知道我该怎么做吗?
谢谢!
最佳答案
仿函数很容易制作。这是在 2011 年之前的 c++ 中柯里化(Currying)函数的唯一方法。
例子:
struct my_func_functor // choose a name
{
int curry_;
my_func_functor(int curry) : curry_(curry) {}
int operator()(int a) { return my_func(a, curry_); }
};
// to use...
vector<int> v;
//...
// build the functor with the curry and let transform do the cooking...
std::transform(v.begin(), v.end(), v.begin(), my_func_functor(555));
您当然可以在仿函数中存储您想要的任何内容。包括引用资料。这与 C++11 的 lambda 在幕后使用的模型相同。当通过 operator()
进行实际调用时,您有一个构造函数和一个用于保存要传递的数据的结构,而不是捕获子句。
关于c++ - 如何在 C++11 之前进行函数柯里化(Currying),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46022071/