lambda表达式(MSVC ++对g ++) [英] lambda expression (MSVC++ vs g++)

查看:269
本文介绍了lambda表达式(MSVC ++对g ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

#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();
}

上述代码在上产生一个错误MSVC ++ 10 ,但它编译正确与 g ++ 4.5
产生的错误是 1 IntelliSense:对lambda体中的外部范围局部变量的无效引用c:\users\super user\documents\visual studio 2010\projects \lambda\lambda.cpp 19 46 lambda

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

因此,是否有任何其他方法访问外部范围而不在本地lambda表达式( std :: for_each )内显式创建新变量

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)?

g ++ 4.5 上,代码编译良好。
标准(n3000草案)说什么?(我目前没有C ++ - 0x(1x?)标准的副本)

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)

推荐答案

你真的尝试过编译代码的问题吗? Visual C ++ 2010接受代码,原样(删除注释,很明显),并成功编译代码没有错误。

Have you actually tried compiling the code in the question? Visual C++ 2010 accepts the code, as is (with the comment removed, obviously), and successfully compiles the code without error.

您看到的错误不是编译错误,而是IntelliSense错误。 IntelliSense错误检查导致大量的误报(我已经报告过几个月Microsoft Connect上的几个错误);在这种情况下,IntelliSense不正确地说这是一个错误,当它不是。

The "error" you are seeing is not a compilation error, but an IntelliSense error. The IntelliSense error checking results in a lot of false positives (I've reported several bugs on Microsoft Connect over the past few months); in this case, IntelliSense is incorrectly saying this is an error when it is not.

有两个选项:你可以忽略IntelliSense误报或你可以禁用IntelliSense错误检查(右键单击错误列表窗口,取消选中显示智能感知错误)。

You have two options: you can ignore the IntelliSense false positives or you can disable the IntelliSense error checking (right-click the Error List window and uncheck "Show IntelliSense Errors").

无论如何,这些IntelliSense错误绝对不会阻止编译成功。

Either way, these IntelliSense errors in no way prevent compilation from succeeding.

这篇关于lambda表达式(MSVC ++对g ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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