I am writing the following recursive lambda function:
#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;
}
...but it doesn't compile:
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)-><lambda(int, int)>::sum`’ cannot be used as a function
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);
};
Could someone throw light on this?
gcc version 4.5.0 20091231 (experimental) (GCC)
mutable
keyword doing there?std::function<int(int,int)> sum = [&](int a, int b) {