VC10中的C++0x特性 Part 1:Lambdas,auto,以及 static_assert
2009-06-10 20:07:49 来源:WEB开发网如果你忘记了capture-list,编译器就会抱怨:
C:Temp>cl /EHsc /nologo /W4 borkedcapturekittybyvalue.cpp
borkedcapturekittybyvalue.cpp
borkedcapturekittybyvalue.cpp(27) : error C3493: 'x' cannot be implicitly captured as no default capture mode has been specified
borkedcapturekittybyvalue.cpp(27) : error C3493: 'y' cannot be implicitly captured as no default capture mode has been specified
(我很快就会解释默认的传递(capture))
记着,lambda 表达式隐式地定义了一个不具名函数对象类。复合声明语句 { return x < n && n < y; } 在这个类中被当作函数调用操作符的函数体。虽然从词法结构上看复合声明语句是在 main() 块之内,但在概念上它是在 main() 块之外的,因此如果不传递(capture)到 lambda 中去,就不能在其中使用来自main() 中的局部变量。
上面的代码在内部被翻译成:
C:Temp>type capturekittybyvalue98.cpp
#include <algorithm>
#include <iostream>
#include <iterator>
#include <ostream>
#include <vector>
using namespace std;
class LambdaFunctor {
public:
LambdaFunctor(int a, int b) : m_a(a), m_b(b) { }
bool operator()(int n) const { return m_a < n && n < m_b; }
private:
int m_a;
int m_b;
};
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
int x = 0;
int y = 0;
cout << "Input: ";
cin >> x >> y; // EVIL!
v.erase(remove_if(v.begin(), v.end(), LambdaFunctor(x, y)), v.end());
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
C:Temp>cl /EHsc /nologo /W4 capturekittybyvalue98.cpp > NUL && capturekittybyvalue98
Input: 4 7
0 1 2 3 4 7 8 9
更多精彩
赞助商链接