【问题标题】:C++ and curryingC++ 和柯里化
【发布时间】:2012-04-07 14:46:16
【问题描述】:

我有代码:

#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

有什么方法可以稍后调用最后一个函数,然后与第一个调用绑定?

【问题讨论】:

  • 你的意思是 auto i = fn(2)?

标签: c++ design-patterns c++11 currying


【解决方案1】:

以下按预期工作

#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

这是了解问题所在的“明显”且有用的信息。

【讨论】:

    【解决方案2】:

    fn 的结果不是整数,因此您不能将 fn(2) 分配给整数(甚至不知道为什么会编译)。

    你应该可以做到auto i = fn(2);

    【讨论】:

    • 确实,它不能编译。至少使用 g++
    • 我的意思当然是int i = fn(2); 不能编译,auto i = fn(2) 可以;我正在使用 g++ 4.5,但奇怪的是 4.7 编译时没有警告int i = fn(2),因为fn(2) 它不是 int
    【解决方案3】:

    这对我有用:

    int main() {
        auto i = fn(2);
        cout << i(4) << endl;  // prints 8
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 2013-11-07
      • 2011-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多