Visual Studio 2010 的 C++ 编译器(VC10)支持六项C++0x新特性:auto、右值引用、static_assert、nullptr、lambda表达式以及decltype。与同样在标准出台之前诞生的VC6相比较,在与标准的契合度这一点上VC10显然有了巨大的进步,但遗憾的是,在功能增强的同时编译器自身也不可避免地引入了不少bug,尤其是关于lambda表达式,下面略举几例。
1.
int main() { struct X {}; auto a = [](){return X();}; }
编译器报错:error C3861: 'X': identifier not found.
规避方案(奇怪)如下:
int main() { struct X {}; typedef X Y; auto a = [](){return Y();}; }
2.
template <typename T> struct dummy { static T foo() { return T(); } }; int main() { typedef dummy<bool> dummy_type; auto x = [](){ bool b = dummy_type::foo(); }; }
编译器报错:error C2653: 'dummy_type' : is not a class or namespace name.
error C3861: 'foo': identifier not found.
规避方案(奇妙)如下:
template <typename T> struct dummy { static T foo() { return T(); } }; int main() { typedef dummy<bool> dummy_type; auto x = [](){ dummy_type d; bool b = d.foo(); }; auto y = [](){ bool b = dummy<bool>::foo(); }; }
3.
int main() { struct X {}; auto y = [](){ X x; }; }
编译器直接崩溃:fatal error C1001: An internal error has occurred in the compiler.
规避方案(正常)如下:
int main() { struct X {}; typedef X Y; auto y = [](){ Y x; }; }
4.
int main() { enum E {A, B, C}; auto x = [](){ int a = A; }; }
编译器报错:error C3493: 'A' cannot be implicitly captured because no default capture mode has been specified.
规避方案(可疑)如下:
int main() { enum E {A, B, C}; auto x = [=](){ int a = A; }; }
5.
int main() { enum E {A, B, C}; auto x = [](){ E a = A; }; }
编译器再一次崩溃:fatal error C1001: An internal error has occurred in the compiler.
综合利用以上学到的“知识”,不难得出以下规避方案:
int main() { enum E {A, B, C}; typedef E F; auto x = [=](){ F a = A; }; }
注:以上“有问题”的代码在gcc4.5中均能编译通过。
注:部分代码摘自StackOverflow: Are function-local typedefs visible inside C++0x lambdas?