lambda 中的 for 循环问题
我目前正在重写我前段时间编写的一个小项目,并用 std::function
和 lambda 替换函数指针。
在执行此操作时,我偶然发现了 lambda 中的 for 循环问题。 在 Visual Studio 2010(带 SP1)中,当在 lambda 内部使用 for 循环时,如果 lambda 是在文件范围内定义的,则会生成奇怪的错误:
#include <iostream>
auto print_sum =
[]( int n )
{
int sum=0;
// line below generates:
// error C2143: syntax error : missing ')' before ';'
for( int i=1; i<=n; ++i )
sum += i;
std::cout << sum << "\n";
};
int main()
{
print_sum(3);
return 0;
}
但是以下代码片段编译良好:
#include <iostream>
int main()
{
auto print_sum =
[]( int n )
{
int sum=0;
for( int i=1; i<=n; ++i )
sum += i;
std::cout << sum << "\n";
};
print_sum(3);
return 0;
}
两个代码片段都使用 MinGW GCC 4.7 编译良好。
还有其他人也观察到这种行为吗? 这是 Visual Studio 的 lambda 实现中的错误吗? 你知道有什么解决方法吗?
编辑:
Microsoft Connect 错误报告:
https://connect.microsoft.com/VisualStudio/feedback/details/660742/error-with-for-loops-in-file-scope-lamdas-c-0x#details
I am currently rewriting a small project i written some time ago, and am replacing function pointers with std::function
and lambdas.
While doing this i stumbled over an issue with for loops in lambdas.
in Visual Studio 2010 (with SP1) generates strange errors when for loops are used inside lambdas, IF the lambda is defined at file scope:
#include <iostream>
auto print_sum =
[]( int n )
{
int sum=0;
// line below generates:
// error C2143: syntax error : missing ')' before ';'
for( int i=1; i<=n; ++i )
sum += i;
std::cout << sum << "\n";
};
int main()
{
print_sum(3);
return 0;
}
following snippet however compiles fine:
#include <iostream>
int main()
{
auto print_sum =
[]( int n )
{
int sum=0;
for( int i=1; i<=n; ++i )
sum += i;
std::cout << sum << "\n";
};
print_sum(3);
return 0;
}
Both snippets compile fine using MinGW GCC 4.7.
Has anyone else observed this behaviour aswell?
Is this a bug in the lambda implementation of the Visual Studio?
Do you know any workarounds?
Edit:
bug report on microsoft connect:
https://connect.microsoft.com/VisualStudio/feedback/details/660742/error-with-for-loops-in-file-scope-lamdas-c-0x#details
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可以在 Visual Studio 2010 RTM 上验证此行为。它似乎仅限于 for 循环,因为以下编译得很好。
上提交错误来提醒微软注意此问题
注意:我不 100 % 知道这是否是一个错误,但有证据表明确实如此
I can verify this behavior on Visual Studio 2010 RTM. It appears to be limited to just for loops as the following compiles just fine.
I would definitely alert microsoft to this issue by filing a bug on connect
Note: I don't 100% know if this is a bug but evidence suggests that it is