官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 内江市| 云林县| 兴宁市| 大兴区| 堆龙德庆县| 凤山县| 准格尔旗| 台州市| 五莲县| 那坡县| 广南县| 镇康县| 丽江市| 汉中市| 嘉定区| 新野县| 水富县| 永寿县| 彩票| 顺昌县| 永顺县| 南京市| 彭阳县| 汉中市| 睢宁县| 凤翔县| 江油市| 安阳市| 永泰县| 普安县| 修水县| 渭南市| 绥中县| 蒲城县| 柳河县| 来凤县| 秦皇岛市| 遂溪县| 玛沁县| 双牌县| 类乌齐县|