在最新版的《C++ Primer》中有這么一句話:若lambda的函數(shù)體包含單一return語(yǔ)句之外的內(nèi)容,且未指定返回類型,則返回void。然后我做了如下測(cè)試:#include?<iostream>
#include?<algorithm>
#include?<vector>
using?namespace?std;
int?main(void)?{
????vector<int>?vi{?1,?-2,?3,?-4,?5,?-6?};
????/*lambda表達(dá)式返回void?*/
????/*標(biāo)準(zhǔn)寫(xiě)法:[](int?i)?->?int?{?
????????????????????????????????????if(i?<?0)?return?-i;?
????????????????????????????????????else?return?i;?}?*/
????transform(vi.begin(),?vi.end(),?vi.begin(),?[](int?i)?{
????????????????????????????????????????????????????if?(i?<?0)?return?-i;
????????????????????????????????????????????????????else?return?i;?});
????for?(int?i?:?vi)
????????cout?<<?i?<<?"?";
????cout?<<?endl;
????system("pause");
????return?0;
}可不管是在Dev-C++中還是在Visual Studio中,它都能正確編譯并且執(zhí)行。如果lambda在這里返回void,就應(yīng)該會(huì)編譯錯(cuò)誤才是???這是為什么呢?然后我在Visual Studio上又添加了這樣的一段代碼:auto?f?=?[](int?i)?{
????????????????????if?(i?<?0)?return?-i;
????????????????????else?return?i;?};在visual assistX的幫助下,鼠標(biāo)移動(dòng)到f,它顯示的返回類型也是int。《C++ Primer》寫(xiě)錯(cuò)的可能性不大,比較可能的是編譯器的問(wèn)題。難道是編譯器都不完全遵循C++標(biāo)準(zhǔn)嗎?或者是C++14有什么新規(guī)定嗎?為防止翻譯的誤差,我也特地找了原版來(lái)看,也是如此的:Lambda with function bodies that contain anything other than a single return statement that do not specify a return type return void.??? via 《C++ Primer》 5th Edition, Page 389.However, if we write the seemingly equivalent program using an if statement, our code won't compile:????//error: can't deduce the return type for the lambda.????transform(vi.begin(), vi.end(), vi.begin(), [](int i) { if(i < 0) return -i; else return i; } );via 《C++ Primer》 5th Edition, Page 396.
4 回答
- 4 回答
- 0 關(guān)注
- 4007 瀏覽
添加回答
舉報(bào)
0/150
提交
取消