C++14嘗鮮:Generic Lambdas(泛型lambda),lambdaslambda

來源:互聯網
上載者:User

C++14嘗鮮:Generic Lambdas(泛型lambda),lambdaslambda
所謂泛型lambda,就是在形參聲明中使用auto類型指示說明符的lambda。比如

auto lambda = [](auto x, auto y) {return x + y;};
根據C++14標準,這一lambda與以下代碼作用相同。
struct unnamed_lambda{  template<typename T, typename U>    auto operator()(T x, U y) const {return x + y;}};auto lambda = unnamed_lambda();
C++14的泛型lambda可以被看做C++11的(單態)lambda的升級版。單態lambda相當於普通函數對象。而泛型lambda則相當於帶模板參數的函數對象,或者說相當於帶狀態的函數模板。兩者相比,可以推出以下結果:可以說,泛型lambda大大加強了C++語言中因單態lambda的引入而有所增強FP(函數型編程)能力。
#include <iostream>#include <vector>#include <algorithm>using namespace std;int main() {// 泛型局部函數auto f = [](auto x, auto y) { return x + y; };cout << f(1, 3) << endl;cout << f(string{}, "abc") << endl;// 泛型回呼函數auto f2 = [](auto e) { cout << e << ","; };vector<int> v1{1, 2, 3};vector<string> v2{"a", "b", "c"};for_each(v1.begin(), v1.end(), f2); cout << endl;for_each(v2.begin(), v2.end(), f2); cout << endl;// 泛型閉包auto f3 = [](auto a) {return [=]() mutable { return a = a + a; };};auto twice1 = f3(1);cout << twice1() << endl; cout << twice1() << endl;auto twice2 = f3(string{"a"});cout << twice2() << endl; cout << twice2() << endl;}/*4abc1,2,3,a,b,c,24aaaaaa*/</string></int>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.