I have the following code
#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>
int main()
{
typedef std::vector<int> Vector;
int sum=0;
Vector v;
for(int i=1;i<=10;++i)
v.push_back(i);
std::tr1::function<double()> l=[&]()->double{
std::for_each(v.begin(),v.end(),[&](int n){sum += n; //Error Here in MSVC++});
return sum;
};
std::cout<<l();
std::cin.get();
}
The above code produces an error on MSVC++ 10
whereas it compiles fine with g++ 4.5
.
The error produced is 1 IntelliSense: invalid reference to an outer-scope local variable in a lambda body c:\users\super user\documents\visual studio 2010\projects\lambda\lambda.cpp 19 46 lambda
So, is there any other way to access the outer-scope variable sum
without explicitly creating a new variable inside the local lambda expression(inside std::for_each
)?
On g++ 4.5
the code compiles fine.
Does the standard(n3000 draft) say anything about it?(I don't have a copy of C++-0x(1x ?) standard at present)