Ops*_*psa 1 c++ design-patterns currying c++11
我有代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这段代码工作正常.但是,我想稍后再调用第二个函数:
auto i = fn(2);
i(4); //error: 'i' cannot be used as a function
Run Code Online (Sandbox Code Playgroud)
有没有办法稍后调用最后一个函数然后绑定第一个调用?
以下按预期工作
#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;
}
Run Code Online (Sandbox Code Playgroud)
加
顺便说一下,如果使用int而不是auto,gcc 4.5和-std = c ++ 0x会出现以下错误:
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
Run Code Online (Sandbox Code Playgroud)
这是一个"明显的"有用的信息,可以解决出错的问题.
| 归档时间: |
|
| 查看次数: |
545 次 |
| 最近记录: |