【譯】VC10中的C++0x特性 Part 1:Lambdas,auto,以及 static_assert
來源:vcblog 作者:Stephan T. Lavavej 翻譯:飄飄白云
(轉(zhuǎn)載時(shí)請注明作者和出處。未經(jīng)許可,請勿用于商業(yè)用途)
簡介
這一系列文章介紹Microsoft Visual Studio 2010 中支持的C++ 0x特性,目前有三部分。
Part 1 :介紹了Lambdas, 賦予新意義的auto,以及 static_assert;
Part 2( 一 , 二 , 三 ):介紹了右值引用(Rvalue References);
Part 3:介紹了表達(dá)式類型(decltype)
VC10中的C++0x特性 Part 1,2,3 譯文打包下載(doc 和 pdf 格式): 點(diǎn)此下載
本文為 Part 1。
Microsoft Visual Studio 2010 九月社區(qū)技術(shù)預(yù)覽版 (CTP)所帶的Visual C++編譯器對四個(gè)C++0x語言特性提供了支持,也就是 lambdas,auto,static_assert,以及 rvalue references (右值引用,譯注:后面不再對這個(gè)詞進(jìn)行翻譯)。今天,我將詳細(xì)介紹前三個(gè)特性。(很快我將貢獻(xiàn)一整篇幅的文章來解釋右值引用,僅僅是因?yàn)樵僭谶@里解釋的話將會加大這篇已經(jīng)很長的文章的篇幅)
首先,說明一些事情:
1,今天的這篇文章是由 Stephan T. Lavavej,Visual C++庫的開發(fā)人員以及C, A, 與 T讀者投書欄帶給你們的。注意作為庫的開發(fā)人員,我并沒有實(shí)現(xiàn)這些特性。那是 Jonathan Caves,前端編譯器開發(fā)者,選舉標(biāo)準(zhǔn)委員會成員以及所有“忍者”(鮮為人知的高手)的成果。
2,我將 Visual C++ compiler in VS 2010 簡稱為 VC10 ( VS 2008 包含 VC9,VS 2005 包含 VC8,等等。 - 10 并不比 2010 簡短)
3,C++0x 指的是即將到來的 C++ 標(biāo)準(zhǔn),現(xiàn)在還在起草中。(C++標(biāo)準(zhǔn)委員會希望它可以在 2009 年完成,稱作 C++ 09;玩笑話說如果它推遲到 2010 或者更晚的話,“x” 將是十六進(jìn)制的了)。 C++ 98 和C++ 03 指的是當(dāng)前的 C++ 標(biāo)準(zhǔn)。(在這里不回顧歷史了, C++ 標(biāo)準(zhǔn) 2003 僅僅是最初的 C++ 1998 標(biāo)準(zhǔn) 的“補(bǔ)丁”版,對大部分人來說可以忽略兩者間的區(qū)別。C++ 03 和 C++ 0x 模樣雖然看起來差不多,但完全不同)
4,我要感謝標(biāo)準(zhǔn)委員會開發(fā)出這些奇妙而有用并富有藝術(shù)的特性。他們也在以下站點(diǎn)上提供了重要的文檔:
C++0x 語言特性:
http://open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2705.html
C++0x 庫特性:
http://open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2706.html
C++0x 進(jìn)行中的草案:
http://open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2798.pdf
5,總是會有bug的(雖然希望不會太多),這也就是發(fā)布 CTP 版本的主要目的(讓用戶測試發(fā)現(xiàn) bug )。請通過 Microfsoft 把這些 bug 報(bào)告給我們。
現(xiàn)在,讓我們來審視這些特性吧!
lambdas
在 C++ 0x 中,“lambda 表達(dá)式”隱式定義并構(gòu)建不具名函數(shù)對象,這些對象就像手寫函數(shù)對象一樣。下面是 lambda “Hello,World”入門級的示例:
C:\Temp>type meow.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
cout << endl;
}
C:\Temp>cl /EHsc /nologo /W4 meow.cpp > NUL && meow
0 1 2 3 4 5 6 7 8 9
[] 操作符是 lambda 導(dǎo)引符, 它告訴編譯器一個(gè) lambda 表達(dá)式開始了。 (int n) 是 lambda 參數(shù)聲明,它告訴編譯器不具名函數(shù)對象類的函數(shù)調(diào)用操作符帶有哪些參數(shù), { cout << n << " "; } 是復(fù)合聲明,它是不具名函數(shù)對象類的函數(shù)調(diào)用操作符的函數(shù)體。不具名函數(shù)對象類的函數(shù)調(diào)用操作符默認(rèn)返回 void。
這樣,C++0x 在內(nèi)部將它轉(zhuǎn)換成如你在C++ 98 下編寫的一樣代碼:
C:\Temp>type meow98.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
struct LambdaFunctor {
void operator()(int n) const {
cout << n << " ";
}
};
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
for_each(v.begin(), v.end(), LambdaFunctor());
cout << endl;
}
C:\Temp>cl /EHsc /nologo /W4 meow98.cpp > NUL && meow98
0 1 2 3 4 5 6 7 8 9
現(xiàn)在我將不再累述類似“不具名函數(shù)對象類的函數(shù)調(diào)用操作符默認(rèn)返回 void”這樣的話,開始換用“lambda 函數(shù)返回 void”的說法,但是記住 lambda 表達(dá)式做了些什么是很重要的,那就是:定義類并構(gòu)建對象。
當(dāng)然,lambda 的復(fù)合聲明部分(函數(shù)體部分)可以包含多個(gè)聲明語句,譬如:
C:\Temp>type multimeow.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
for_each(v.begin(), v.end(), [](int n) {
cout << n;
if (n % 2 == 0) {
cout << " even ";
} else {
cout << " odd ";
}
});
cout << endl;
}
C:\Temp>cl /EHsc /nologo /W4 multimeow.cpp > NUL && multimeow
0 even 1 odd 2 even 3 odd 4 even 5 odd 6 even 7 odd 8 even 9 odd
lambda 函數(shù)也并不總是必須返回 void。如果 lambda 的復(fù)合聲明語句像是這樣的 { return expression; } ,那么 lambda 的返回類型就會自動地被推斷成 expression 的類型。
C:\Temp>type cubicmeow.cpp
#include <algorithm>
#include <deque>
#include <iostream>
#include <iterator>
#include <ostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
deque<int> d;
transform(v.begin(), v.end(), front_inserter(d), [](int n) { return n * n * n; });
for_each(d.begin(), d.end(), [](int n) { cout << n << " "; });
cout << endl;
}
C:\Temp>cl /EHsc /nologo /W4 cubicmeow.cpp > NUL && cubicmeow
729 512 343 216 125 64 27 8 1 0
在這里, n * n * n 的類型是 int,所以 lambda 函數(shù)返回 int。
有著復(fù)雜復(fù)合聲明語句的 lambda 函數(shù)不會自動推斷返回類型,你必須顯式指定返回類型。
C:\Temp>type returnmeow.cpp
#include <algorithm>
#include <deque>
#include <iostream>
#include <iterator>
#include <ostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
deque<double> d;
transform(v.begin(), v.end(), front_inserter(d), [](int n) -> double {
if (n % 2 == 0) {
return n * n * n;
} else {
return n / 2.0;
}
});
for_each(d.begin(), d.end(), [](double x) { cout << x << " "; });
cout << endl;
}
C:\Temp>cl /EHsc /nologo /W4 returnmeow.cpp > NUL && returnmeow
4.5 512 3.5 216 2.5 64 1.5 8 0.5 0
-> double 是可選的 lambda 返回類型從句。為什么它不放在左邊(譯注:返回類型一般在函數(shù)左邊聲明),就像程序員一直以來在C函數(shù)中做的那樣?因?yàn)槟菢拥脑?lambda 導(dǎo)引符 [] 就不會第一個(gè)出現(xiàn)了,而正是它告訴編譯器一個(gè) lambda 函數(shù)開始了。(核心工作組最擅長解決這樣的問題;嘗試猜測C++ 中一個(gè)給定的概念是否是可被解析的會讓我頭疼。)
如果忘記了指定 lambda返回類型從句,編譯器就會抱怨每一個(gè)返回語句:
C:\Temp>cl /EHsc /nologo /W4 borkedreturnmeow.cpp
borkedreturnmeow.cpp
borkedreturnmeow.cpp(20) : error C3499: a lambda that has been specified to have a void return type cannot return a value
borkedreturnmeow.cpp(22) : error C3499: a lambda that has been specified to have a void return type cannot return a value
到目前為止我所介紹的 lambda 都是無狀態(tài)的:它們不包含數(shù)據(jù)成員。你也可以有有狀態(tài)的 lambda,這是通過“傳遞”(原文用加引號的 capturing 這個(gè)詞,在這里我翻譯成傳遞似乎不太妥,故我都加括號引用原文,下同)局部變量來實(shí)現(xiàn)的。空的 lambda 導(dǎo)引符 [] 意味著“一個(gè)無狀態(tài)的 lambda”,但在 lambda 導(dǎo)引符 [] 中你可以指定 capture-list :
C:\Temp>type capturekittybyvalue.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
int x = 0;
int y = 0;
// op>>() leaves newlines on the input stream,
// which can be extremely confusing. I recommend
// avoiding it, and instead using non-member
// getline(cin, str) to read whole lines and
// then parse them. But in the interests of
// brevity, I'll use evil op>>():
cout << "Input: ";
cin >> x >> y;
v.erase(remove_if(v.begin(), v.end(), [x, y](int n) { return x < n && n < y; }), v.end());
for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
cout << endl;
}
C:\Temp>cl /EHsc /nologo /W4 capturekittybyvalue.cpp > NUL && capturekittybyvalue
Input: 4 7
0 1 2 3 4 7 8 9
如果你忘記了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
(我很快就會解釋默認(rèn)的傳遞(capture))
記著,lambda 表達(dá)式隱式地定義了一個(gè)不具名函數(shù)對象類。復(fù)合聲明語句 { return x < n && n < y; } 在這個(gè)類中被當(dāng)作函數(shù)調(diào)用操作符的函數(shù)體。雖然從詞法結(jié)構(gòu)上看復(fù)合聲明語句是在 main() 塊之內(nèi),但在概念上它是在 main() 塊之外的,因此如果不傳遞(capture)到 lambda 中去,就不能在其中使用來自main() 中的局部變量。
上面的代碼在內(nèi)部被翻譯成:
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
在這里你可以清楚地看到是“按值”傳遞(captures)的。函數(shù)對象存儲了局部變量的拷貝。這就使得函數(shù)對象可以比通過傳遞(capture)來創(chuàng)建它們的局部變量有更長的生命期。但是,要注意:(a)在 lambda 中不能修改通過傳遞(capture)獲得的拷貝,因?yàn)槟J(rèn)情況下函數(shù)調(diào)用操作符是 const 屬性的,(b)一些對象的拷貝開銷是昂貴的,(c)局部變量的更新不會反應(yīng)到通過傳遞(capture)獲得的拷貝(在語義上它們是原始值)。很快我就會解釋如有需要應(yīng)該如何來處理以上情況。
但是首先,你可以“按值傳遞(capture)任何東西”,而不用特別指明每一個(gè)你想要傳遞(capture)的局部變量。其語法是使用這種形式的 lambda 導(dǎo)引符 [=] (默認(rèn)傳遞(capture-default) = 應(yīng)該可以讓你想起賦值或者拷貝初始化 Foo foo = bar; 雖然這里的拷貝實(shí)際上是直接初始化(通過初始化列表進(jìn)行賦值),就像上面的 m_a(a))。
C:\Temp>type defaultcapturekittybyvalue.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
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(), [=](int n) { return x < n && n < y; }), v.end());
for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
cout << endl;
}
C:\Temp>cl /EHsc /nologo /W4 defaultcapturekittybyvalue.cpp > NUL && defaultcapturekittybyvalue
Input: 4 7
0 1 2 3 4 7 8 9
當(dāng)編譯器看到 lambda 中的 x 和 y, 就會從 main() 中按值傳遞(capture)。
情形(a)要修改通過傳遞(capture)獲得拷貝該怎樣呢?默認(rèn)情況下,一個(gè) lambda 函數(shù)調(diào)用操作符是 const 屬性的,但是可以通過使用 mutable 把它變成 non-const。
C:\Temp>type capturekittybymutablevalue.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
int x = 1;
int y = 1;
for_each(v.begin(), v.end(), [=](int& r) mutable {
const int old = r;
r *= x * y;
x = y;
y = old;
});
for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
cout << endl;
cout << x << ", " << y << endl;
}
C:\Temp>cl /EHsc /nologo /W4 capturekittybymutablevalue.cpp > NUL && capturekittybymutablevalue
0 0 0 6 24 60 120 210 336 504
1, 1
這里是依次將 v 中前兩個(gè)元素相乘。(我得承認(rèn)真的很難想出一個(gè)不用 partial_sum() 或 adjacent_difference() 表示的例子,partial_sum() 是與前面所有的元素相乘,adjacent_difference()是與前一個(gè)元素相乘)。注意到情形(d),對通過傳遞獲得的拷貝的更新操作并沒有影響局部變量(再一次,原始值語義)。
如果你想處理情形(b),(c)和(d):避免拷貝,在 lambda 中觀察局部變量的更新,以及在 lambda 中修改局部變量又該怎么做呢?在這種情況下,你會想通過引用傳遞(capture by reference)。其語法是這種形式的 lambda 導(dǎo)引符 [&x, &y] (你可以把它想象成 X& x, Y& y ; 那是“引用”而不是“取址”)。
C:\Temp>type capturekittybyreference.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
int x = 1;
int y = 1;
for_each(v.begin(), v.end(), [&x, &y](int& r) {
const int old = r;
r *= x * y;
x = y;
y = old;
});
for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
cout << endl;
cout << x << ", " << y << endl;
}
C:\Temp>cl /EHsc /nologo /W4 capturekittybyreference.cpp > NUL && capturekittybyreference
0 0 0 6 24 60 120 210 336 504
8, 9
注意與 capturekittybymutablevalue.cpp 的區(qū)別:(1),lambda 導(dǎo)引符是 [&x, &y] ,(2)沒有 mutable,(3),局部變量 x 和 y 最后的值是 8 和 9,反應(yīng)了在 lambda 中對他們的修改。
上面的代碼在內(nèi)部被翻譯成:
C:\Temp>type capturekittybyreference98.cpp
#include <algorithm>
#include <iostream>
#include <iterator>
#include <ostream>
#include <vector>
using namespace std;
#pragma warning(push)
#pragma warning(disable: 4512) // assignment operator could not be generated
class LambdaFunctor {
public:
LambdaFunctor(int& a, int& b) : m_a(a), m_b(b) { }
void operator()(int& r) const {
const int old = r;
r *= m_a * m_b;
m_a = m_b;
m_b = old;
}
private:
int& m_a;
int& m_b;
};
#pragma warning(pop)
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
int x = 1;
int y = 1;
for_each(v.begin(), v.end(), LambdaFunctor(x, y));
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << endl;
cout << x << ", " << y << endl;
}
C:\Temp>cl /EHsc /nologo /W4 capturekittybyreference98.cpp > NUL && capturekittybyreference98
0 0 0 6 24 60 120 210 336 504
8, 9
當(dāng)你通過引用傳遞(capture)局部變量時(shí),函數(shù)對象存儲局部變量的引用。這樣避免了拷貝,能夠讓函數(shù)對象觀測對局部變量的更新,以及能夠讓函數(shù)對象通過引用修改局部變量。(注意函數(shù)調(diào)用操作符是 const 屬性的,因?yàn)槲覀儧]有把它聲明成 mutable,但這只阻止我們修改函數(shù)對象的數(shù)據(jù)成員。在這里數(shù)據(jù)成員是引用,我們無法修改它,但是我們可以修改它所指向的東西。函數(shù)調(diào)用操作符的常量性是,且一直都是,表面的)
當(dāng)然,如果函數(shù)對象比用于引用傳遞的局部變量的生命期更長的話,程序會毀滅性地崩潰。(譯注:就是說引用所指向的東西已經(jīng)銷毀了,但你可能還在使用這個(gè)引用)
同樣,你可以使用默認(rèn)的按引用傳遞語法;這種形式 lambder 導(dǎo)引符 [&] 表明“按引用傳遞”。
如果你想混合使用按值傳遞和按引用傳遞該怎么做呢?你可以像這樣聲明 [a, b, c, &d, e, &f, g],但你也可以指定默認(rèn)按值傳遞,再為特定的(需要按引用傳遞的)局部變量而重載它。下面是一個(gè)修改capturekittybymutablevalue.cpp 而來的例子:
C:\Temp>type overridekitty.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
int sum = 0;
int product = 1;
int x = 1;
int y = 1;
for_each(v.begin(), v.end(), [=, &sum, &product](int& r) mutable {
sum += r;
if (r != 0) {
product *= r;
}
const int old = r;
r *= x * y;
x = y;
y = old;
});
for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
cout << endl;
cout << "sum: " << sum << ", product: " << product << endl;
cout << "x: " << x << ", y: " << y << endl;
}
C:\Temp>cl /EHsc /nologo /W4 overridekitty.cpp && overridekitty
overridekitty.cpp
0 0 0 6 24 60 120 210 336 504
sum: 45, product: 362880
x: 1, y: 1
在這里,我們想通過按值傳遞 x 和 y (因?yàn)槲覀冎幌朐?lambda 內(nèi)部修改它們,而影響外部),同時(shí)我們想按傳引用捕獲 sum 和 product(因?yàn)槲覀兇_實(shí)想讓對它們的修改在外部也生效)。像這樣的 lambda 導(dǎo)入符組合 [&, x, y] 可以起到同樣的效果(按應(yīng)用傳遞所有參數(shù),除了 x 和 y 是按值傳遞之外)
嗯,如果你想這么做又該如何?
C:\Temp>type memberkitty.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
class Kitty {
public:
explicit Kitty(int toys) : m_toys(toys) { }
void meow(const vector<int>& v) const {
for_each(v.begin(), v.end(), [m_toys](int n) {
cout << "If you gave me " << n << " toys, I would have " << n + m_toys << " toys total." << endl;
});
}
private:
int m_toys;
};
int main() {
vector<int> v;
for (int i = 0; i < 3; ++i) {
v.push_back(i);
}
Kitty k(5);
k.meow(v);
}
C:\Temp>cl /EHsc /nologo /W4 memberkitty.cpp
memberkitty.cpp
memberkitty.cpp(12) : error C3480: 'Kitty::m_toys': a lambda capture variable must be from an enclosing function scope
lambda 表達(dá)式語法允許你傳遞局部變量,但是數(shù)據(jù)成員不是局部變量。通過特別的方法,你也可以傳遞數(shù)據(jù)成員:
C:\Temp>type workingmemberkitty.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
class Kitty {
public:
explicit Kitty(int toys) : m_toys(toys) { }
void meow(const vector<int>& v) const {
for_each(v.begin(), v.end(), [this](int n) {
cout << "If you gave me " << n << " toys, I would have " << n + m_toys << " toys total." << endl;
});
}
private:
int m_toys;
};
int main() {
vector<int> v;
for (int i = 0; i < 3; ++i) {
v.push_back(i);
}
Kitty k(5);
k.meow(v);
}
C:\Temp>cl /EHsc /nologo /W4 workingmemberkitty.cpp > NUL && workingmemberkitty
If you gave me 0 toys, I would have 5 toys total.
If you gave me 1 toys, I would have 6 toys total.
If you gave me 2 toys, I would have 7 toys total.
當(dāng)你傳遞 this,你可以使用 m_toys,它隱含意味著 this->m_toys,就如平常一樣(譯注:作為類自身成員變量)。你也可以顯式使用 this->m_toys。(在一個(gè) lambda 表達(dá)式內(nèi),只有當(dāng)你傳遞了 this,你才能使用它;你永不可能取得 lambda 對象它自身的 this 指針)。
你也可以隱式地傳遞 this :
C:\Temp>type implicitmemberkitty.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
class Kitty {
public:
explicit Kitty(int toys) : m_toys(toys) { }
void meow(const vector<int>& v) const {
for_each(v.begin(), v.end(), [=](int n) {
cout << "If you gave me " << n << " toys, I would have " << n + m_toys << " toys total." << endl;
});
}
private:
int m_toys;
};
int main() {
vector<int> v;
for (int i = 0; i < 3; ++i) {
v.push_back(i);
}
Kitty k(5);
k.meow(v);
}
C:\Temp>cl /EHsc /nologo /W4 implicitmemberkitty.cpp > NUL && implicitmemberkitty
If you gave me 0 toys, I would have 5 toys total.
If you gave me 1 toys, I would have 6 toys total.
If you gave me 2 toys, I would have 7 toys total.
你可以使用 [&],但它對傳遞是怎樣進(jìn)行的(默認(rèn)是按值)沒有影響。你不能使用 [&this]。
如果你想使用一個(gè)空無的 lambda (不帶參數(shù)),你可以省略整個(gè) lambda參數(shù)聲明:
C:\Temp>type nullarykitty.cpp
#include <algorithm>
#include <iostream>
#include <iterator>
#include <ostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
int i = 0;
generate_n(back_inserter(v), 10, [&] { return i++; });
for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
cout << endl;
cout << "i: " << i << endl;
}
C:\Temp>cl /EHsc /nologo /W4 nullarykitty.cpp > NUL && nullarykitty
0 1 2 3 4 5 6 7 8 9
i: 10
這比 [&]() { return i++; } 少兩個(gè)字符。省略 lambda 參數(shù)聲明是否是良好的風(fēng)格是由你來決定的。
僅博一笑,這意味著下面的代碼在 C++0x 中是合法的。
C:\Temp>type nokitty.cpp
int main() {
[](){}();
[]{}();
}
上面構(gòu)建了兩個(gè)什么也不做的 lambda (一個(gè)有 lambda 參數(shù)聲明,一個(gè)沒有)并立即調(diào)用它們(通過最后一個(gè)空括號組合)。
注意可選的 lambda 參數(shù)聲明語法上包括:
( lambda-parameter-declaration-listopt ) mutableopt exception-specificationopt lambda-return-type-clauseopt
因此,如果你想使用 mutable 或 -> ReturnType,你需要在 lambda 導(dǎo)引符和它們之間插入空括號。
最后,因?yàn)?lambda 產(chǎn)生普通的函數(shù)對象,你可以在 tr1::function 中存儲它們。
C:\Temp>type tr1kitty.cpp
#include <algorithm>
#include <functional>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
using namespace std::tr1;
void meow(const vector<int>& v, const function<void (int)>& f) {
for_each(v.begin(), v.end(), f);
cout << endl;
}
int main() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
meow(v, [](int n) { cout << n << " "; });
meow(v, [](int n) { cout << n * n << " "; });
function<void (int)> g = [](int n) { cout << n * n * n << " "; };
meow(v, g);
}
C:\Temp>cl /EHsc /nologo /W4 tr1kitty.cpp > NUL && tr1kitty
0 1 2 3 4 5 6 7 8 9
0 1 4 9 16 25 36 49 64 81
0 1 8 27 64 125 216 343 512 729
auto
關(guān)鍵詞 auto 是從 C++ 98 得來的,它在 C++ 98 中實(shí)際上并沒起什么作用,但在 C++ 0x 中被重用于自動類型推導(dǎo)(automatic type deduction)。 在一個(gè)聲明中使用 auto ,意味著“讓它和初始化它的事物具有相同的類型”。你看:
C:\Temp>type autocat.cpp
#include <iostream>
#include <map>
#include <ostream>
#include <regex>
#include <string>
using namespace std;
using namespace std::tr1;
int main() {
map<string, string> m;
const regex r("(\\w+) (\\w+)");
for (string s; getline(cin, s); ) {
smatch results;
if (regex_match(s, results, r)) {
m[results[1]] = results[2];
}
}
for (auto i = m.begin(); i != m.end(); ++i) {
cout << i->second << " are " << i->first << endl;
}
}
C:\Temp>cl /EHsc /nologo /W4 autocat.cpp > NUL && autocat
cute kittens
ugly puppies
evil goblins
^Z
kittens are cute
goblins are evil
puppies are ugly
map<string, string>::iterator,你近10年的恐怖統(tǒng)治終于到頭了。
(注意:m.begin()返回 iterator,而不是 cosnt_iterator,因?yàn)?map 不是 const 屬性的。C++ 0x cbegin() 允許你從一個(gè) non-cosnt 容器中獲得一個(gè) const_iterator。)
lambdas and auto
先前我提到過在 tr1::functions 中存儲 lambda 函數(shù)。但是如非必要請別這么做,因?yàn)?tr1::function 會增加一些開銷。如果你想重用 lambda 函數(shù),或只想給它命名的話,你可以使用 auto。這兒有一個(gè)簡潔的例子:
C:\Temp>type autolambdakitty.cpp
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
template <typename T, typename Predicate> void keep_if(vector<T>& v, Predicate pred) {
auto notpred = [&](const T& t) {
return !pred(t);
};
v.erase(remove_if(v.begin(), v.end(), notpred), v.end());
}
template <typename Container> void print(const Container& c) {
for_each(c.begin(), c.end(), [](const typename Container::value_type& e) { cout << e << " "; });
cout << endl;
}
int main() {
vector<int> a;
for (int i = 0; i < 100; ++i) {
a.push_back(i);
}
vector<int> b;
for (int i = 100; i < 200; ++i) {
b.push_back(i);
}
auto prime = [](const int n) -> bool {
if (n < 2) {
return false;
}
for (int i = 2; i <= n / i; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
};
keep_if(a, prime);
keep_if(b, prime);
print(a);
print(b);
}
C:\Temp>cl /EHsc /nologo /W4 autolambdakitty.cpp
autolambdakitty.cpp
C:\Temp>autolambdakitty
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
notpred 是一個(gè)否定 lambda 函數(shù),注意我們不能使用 C++ 98 <functional>中的 not1() 函數(shù),因?yàn)槟且竽愕闹^詞函數(shù)繼承自 unary_function,而 lambda 函數(shù)并不滿足這個(gè)條件。
static_assert
static_assert 讓你能夠在觸發(fā)編譯器錯(cuò)誤時(shí)使用定制的錯(cuò)誤信息:
C:\Temp>type staticfluffykitten.cpp
template <int N> struct Kitten {
static_assert(N < 2, "Kitten<N> requires N < 2.");
};
int main() {
Kitten<1> peppermint;
Kitten<3> jazz;
}
C:\Temp>cl /EHsc /nologo /W4 staticfluffykitten.cpp
staticfluffykitten.cpp
staticfluffykitten.cpp(2) : error C2338: Kitten<N> requires N < 2.
staticfluffykitten.cpp(8) : see reference to class template instantiation 'Kitten<N>' being compiled
with
[
N=3
]
如果你有任何疑問,我很樂意在評論中回答它們。
Stephan T. Lavavej
Visual C++ Libraries Developer
Published Tuesday, October 28, 2008 9:31 AM by vcblog
(轉(zhuǎn)載時(shí)請注明作者和出處。未經(jīng)許可,請勿用于商業(yè)用途)