- Learning C++ Functional Programming
- Wisnu Anggoro
- 299字
- 2021-07-02 20:51:38
Writing a generic Lambda expression to be used many times with many different data types
Before C++14, we have to specifically state the type of the parameter list. Fortunately, now in C++14, Lambda expressions accept auto as a valid parameter type. Therefore, we can now build a generic Lambda expression as demonstrated in the following code. In that code, we have only one Lambda expression to find out which is the greatest value between two numbers passed to the expression. We will use the auto keyword in parameter declaration so it can be passed by any data type. Therefore, the findMax() function parameters can be passed by both the int and float data type. The code should be as follows:
/* lambda_expression_generic.cpp */
#include <iostream>
using namespace std;
auto main() -> int
{
cout << "[lambda_expression_generic.cpp]" << endl;
// Creating a generic lambda expression
auto findMax = [](auto &x, auto &y){
return x > y ? x : y; };
// Initializing various variables
int i1 = 5, i2 = 3;
float f1 = 2.5f, f2 = 2.05f;
// Consuming generic lambda expression
// using integer data type
cout << "i1 = 5, i2 = 3" << endl;
cout << "Max: " << findMax(i1, i2) << endl << endl;
// Consuming generic lambda expression
// using double data type
cout << "f1 = 2.5f, f2 = 2.05f" << endl;
cout << "Max: " << findMax(f1, f2) << endl << endl;
return 0;
}
The output we will see on the console should be as follows:

The C++17 language plans to introduce two new features for the Lambda expression--they are capturing *this, which allows the expression to capture the enclosing object by copy, and the constexpr Lambda expressions, which allows us to use the result of the Lambda expressions and generate constexpr objects at compile time. However, since C++17 has not been released yet, we cannot try it for now.
推薦閱讀
- Getting Started with Citrix XenApp? 7.6
- TypeScript Blueprints
- Building Modern Web Applications Using Angular
- Learn to Create WordPress Themes by Building 5 Projects
- Vue.js 2 and Bootstrap 4 Web Development
- AWS Serverless架構:使用AWS從傳統部署方式向Serverless架構遷移
- Flink SQL與DataStream入門、進階與實戰
- BeagleBone Media Center
- 深入淺出DPDK
- C# and .NET Core Test Driven Development
- Mastering Python Design Patterns
- Access 2010數據庫應用技術實驗指導與習題選解(第2版)
- 青少年學Python(第2冊)
- Java并發實現原理:JDK源碼剖析
- HTML5 Canvas核心技術:圖形、動畫與游戲開發