递归lambda函数在C ++ 11 [英] Recursive lambda functions in C++11

查看:124
本文介绍了递归lambda函数在C ++ 11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++ 11的新手。我写了以下递归lambda函数,但它不编译。

I am new to C++11. I am writing the following recursive lambda function, but it doesn't compile.

#include <iostream>
#include <functional>

auto term = [](int a)->int {
  return a*a;
};

auto next = [](int a)->int {
  return ++a;
};

auto sum = [term,next,&sum](int a, int b)mutable ->int {
  if(a>b)
    return 0;
  else
    return term(a) + sum(next(a),b);
};

int main(){
  std::cout<<sum(1,10)<<std::endl;
  return 0;
}



编译错误:



vimal @ linux-718q:〜/ Study / 09C ++ / c ++ 0x / lambda> g ++ -std = c ++ 0x sum.cpp

compilation error:

vimal@linux-718q:~/Study/09C++/c++0x/lambda> g++ -std=c++0x sum.cpp

sum.cpp :in lambda function:
sum.cpp:18:36:error:'((< lambda(int,int)> *)this) - & ,int)> :: sum '不能用作函数

sum.cpp: In lambda function: sum.cpp:18:36: error: ‘((<lambda(int, int)>*)this)-><lambda(int, int)>::sum’ cannot be used as a function

gcc version 4.5.0 20091231(experimental)(GCC)

gcc version 4.5.0 20091231 (experimental) (GCC)

但是如果我改变 sum c $ c>如下,它的工作原理:

But if I change the declaration of sum() as below, it works:

std::function<int(int,int)> sum = [term,next,&sum](int a, int b)->int {
   if(a>b)
     return 0;
   else
     return term(a) + sum(next(a),b);
};

有人可以点亮这个吗?

推荐答案

请考虑自动版本和完全指定的类型版本之间的区别。 auto 关键字推断它的初始化类型,但是你初始化它的类型需要知道它的类型(在这种情况下,lambda闭包需要知道它捕获的类型) 。一个鸡蛋问题和一个鸡蛋问题。

Think about the difference between the auto version and the fully specified type version. The auto keyword infers its type from whatever it's initialized with, but what you're initializing it with needs to know what its type is (in this case, the lambda closure needs to know the types it's capturing). Something of a chicken-and-egg problem.

另一方面,完全指定的函数对象的类型不需要知道什么关于什么被分配因此,lambda的闭包同样可以完全了解它捕获的类型。

On the other hand, a fully specified function object's type doesn't need to "know" anything about what is being assigned to it, and so the lambda's closure can likewise be fully informed about the types its capturing.

考虑对你的代码稍作修改,它可能更有意义: p>

Consider this slight modification of your code and it may make more sense:

std::function<int(int,int)> sum;
sum = [term,next,&sum](int a, int b)->int {
if(a>b)
    return 0;
else
    return term(a) + sum(next(a),b);
};

显然,这不适用于自动。递归lambda函数工作得很好(至少他们在MSVC中,我有他们的经验),只是他们不真正兼容类型推理。

Obviously, this wouldn't work with auto. Recursive lambda functions work perfectly well (at least they do in MSVC, where I have experience with them), it's just that they aren't really compatible with type inference.

这篇关于递归lambda函数在C ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆