我有代码:
#include <iostream>
using namespace std;
auto fn = ([](int x){
return [x](int y) {
return x * y;
};
});
int main() {
int i = fn(2)(4); // 8
cout << i << endl;
return 0;
}
这段代码工作正常。 但是,我想稍后再调用第二个函数,例如:
auto i = fn(2);
i(4); //error: 'i' cannot be used as a function
有什么方法可以稍后调用最后一个函数,然后与第一个调用绑定(bind)?
最佳答案
以下按预期工作
#include <iostream>
using namespace std;
auto fn = [](int x){
return [x](int y) {
return x * y;
};
};
int main() {
auto i = fn(2)(4); // 8
cout << i << endl;
auto j = fn(2);
cout << j(4) << endl;
return 0;
}
添加
顺便说一下,如果您使用 int 而不是 auto,带有 -std=c++0x 的 gcc 4.5 会给出以下错误:
currying.cpp:17:17: error: cannot convert ‘<lambda(int)>::<lambda(int)>’ to ‘int’ in initialization
currying.cpp:19:16: error: ‘j’ cannot be used as a function
这是一个“明显”且有用的信息,可以找出问题所在。
关于C++ 和柯里化(Currying),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10055416/