c++ - 如何在 C++11 之前进行函数柯里化(Currying)

标签 c++

我有一个有两个参数的函数,我想将第二个参数绑定(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/

相关文章:

c++ - 根据迭代器声明容器 const 或 non-const

c++ - 在cpp中格式化

c++ - 在 Buck 中,如何扩展 genrule 输出目录?

c++ - 如何捕获父进程中的Term操作信号?

c++ - 在 C++ 中使用在 masm 中编译的 lib

c++ - 查看visual studio 2010中一个线程获得了多少锁?

c++ - 稍后可以在 Windows 上的 Winsock2 C++ 中修改传递给 Listen() 调用的积压值而不关闭监听套接字吗?

c++ - 分配器 C++ VS 2013

c++ - 数组在返回时丢失值(库存/菜单程序)C++

c++ - 返回后指针不会返回到函数的引用(保持为空)C++