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