C++14 中的泛型 lambda 表示式
在 C++11 中,引入了 lambda。Lambda 基本上是程式碼的一部分,可以巢狀在其他函式呼叫語句中。透過將 lambda 表示式與 auto 關鍵字結合使用,可以供以後使用。
在 C++14 中,這些 lambda 表示式得到改進。在這裡我們可以得到泛型 lambda。例如,如果我們要建立可以加整數、加數字、還可以連線字串的 lambda,那麼我們必須使用這個泛型 lambda。
lambda 表示式的語法如下所示
[](auto x, auto y) { return x + y; }讓我們看一個更好的示例。
示例
#include <iostream>
#include <string>
using namespace std;
main() {
auto add = [](auto arg1, auto arg2) { //define generalized lambda
return arg1 + arg2;
};
cout << "Sum of integers: " << add(5, 8) << endl;
cout << "Sum of floats: " << add(2.75, 5.639) << endl;
cout << "Concatenate Strings: " << add(string("Hello "), string("World")) << endl;
}輸出
Sum of integers: 13 Sum of floats: 8.389 Concatenate Strings: Hello World
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP