客户管理系统开发定制C ++ Lambda表达式详解

C ++ 客户管理系统开发定制表达式详解

1.Lambda客户管理系统开发定制表达式概述

​ Lambda客户管理系统开发定制表达式是现代C++在C ++ 11客户管理系统开发定制和更高版本中的一个新的语法糖 ,在C++11、C++14、C++17和C++20中Lambda客户管理系统开发定制表达的内容还在不断更新。 lambda表达式(也称为lambda函数)客户管理系统开发定制是在调用或作为函数参客户管理系统开发定制数传递的位置处定义匿客户管理系统开发定制名函数对象的便捷方法。通常,lambda客户管理系统开发定制用于封装传递给算法或客户管理系统开发定制异步方法的几行代码 。客户管理系统开发定制本文主要介绍Lambda的工作原理以及使用方法。

2.Lambda表达式定义

2.1 Lambda表达式示例

​ Lambda有很多叫法,有Lambda表达式、Lambda函数、匿名函数,本文中为了方便表述统一用Lambda表达式进行叙述。 ISO C ++标准官网展示了一个简单的lambda 表示式实例:

#include <algorithm>#include <cmath>void abssort(float* x, unsigned n) {    std::sort(x, x + n,        // Lambda expression begins        [](float a, float b) {            return (std::abs(a) < std::abs(b));        } // end of lambda expression    );}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在上面的实例中std::sort函数第三个参数应该是传递一个排序规则的函数,但是这个实例中直接将排序函数的实现写在应该传递函数的位置,省去了定义排序函数的过程,对于这种不需要复用,且短小的函数,直接传递函数体可以增加代码的可读性。

2.2 Lambda表达式语法定义

  1. 捕获列表。在C ++规范中也称为Lambda导入器, 捕获列表总是出现在Lambda函数的开始处。实际上,[]是Lambda引出符。编译器根据该引出符判断接下来的代码是否是Lambda函数,捕获列表能够捕捉上下文中的变量以供Lambda函数使用。
  2. 参数列表。与普通函数的参数列表一致。如果不需要参数传递,则可以连同括号“()”一起省略。
  3. 可变规格*。mutable修饰符, 默认情况下Lambda函数总是一个const函数,mutable可以取消其常量性。在使用该修饰符时,参数列表不可省略(即使参数为空)。*
  4. 异常说明。用于Lamdba表达式内部函数抛出异常。
  5. 返回类型。 追踪返回类型形式声明函数的返回类型。我们可以在不需要返回值的时候也可以连同符号”->”一起省略。此外,在返回类型明确的情况下,也可以省略该部分,让编译器对返回类型进行推导。
  6. lambda函数体。内容与普通函数一样,不过除了可以使用参数之外,还可以使用所有捕获的变量。

2.3 Lambda表达式参数详解

2.3.1 Lambda捕获列表

​ Lambda表达式与普通函数最大的区别是,除了可以使用参数以外,Lambda函数还可以通过捕获列表访问一些上下文中的数据。具体地,捕捉列表描述了上下文中哪些数据可以被Lambda使用,以及使用方式(以值传递的方式或引用传递的方式)。语法上,在“[]”包括起来的是捕获列表,捕获列表由多个捕获项组成,并以逗号分隔。捕获列表有以下几种形式:

  • []表示不捕获任何变量
auto function = ([]{		std::cout << "Hello World!" << std::endl;	});function();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • [var]表示值传递方式捕获变量var

    int num = 100;auto function = ([num]{		std::cout << num << std::endl;	});function();
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • [=]表示值传递方式捕获所有父作用域的变量(包括this)

    int index = 1;int num = 100;auto function = ([=]{			std::cout << "index: "<< index << ", "                 << "num: "<< num << std::endl;	});function();
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  • [&var]表示引用传递捕捉变量var

    int num = 100;auto function = ([&num]{		num = 1000;		std::cout << "num: " << num << std::endl;	});function();
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • [&]表示引用传递方式捕捉所有父作用域的变量(包括this)

    int index = 1;int num = 100;auto function = ([&]{		num = 1000;		index = 2;		std::cout << "index: "<< index << ", "             << "num: "<< num << std::endl;	});function();
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • [this]表示值传递方式捕捉当前的this指针

    #include <iostream>using namespace std; class Lambda{public:    void sayHello() {        std::cout << "Hello" << std::endl;    };    void lambda() {        auto function = [this]{             this->sayHello();         };        function();    }}; int main(){    Lambda demo;    demo.lambda();}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
  • [=, &] 拷贝与引用混合

    • [=,&a,&b]表示以引用传递的方式捕捉变量a和b,以值传递方式捕捉其它所有变量。

      int index = 1;int num = 100;auto function = ([=, &index, &num]{		num = 1000;		index = 2;		std::cout << "index: "<< index << ", "             << "num: "<< num << std::endl;	});function();
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
    • 1
  • [&,a,this]表示以值传递的方式捕捉变量a和this,引用传递方式捕捉其它所有变量。

不过值得注意的是,捕捉列表不允许变量重复传递。下面一些例子就是典型的重复,会导致编译时期的错误。例如:

  • [=,a]这里已经以值传递方式捕捉了所有变量,但是重复捕捉a了,会报错的;

  • [&,&this]这里&已经以引用传递方式捕捉了所有变量,再捕捉this也是一种重复。

如果lambda主体total通过引用访问外部变量,并factor通过值访问外部变量,则以下捕获子句是等效的:

[&total, factor][factor, &total][&, factor][factor, &][=, &total][&total, =]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2.3.2 Lambda参数列表

​ 除了捕获列表之外,lambda还可以接受输入参数。参数列表是可选的,并且在大多数方面类似于函数的参数列表。

auto function = [] (int first, int second){    return first + second;};	function(100, 200);
  • 1
  • 2
  • 3
  • 4
  • 5

2.3.3 可变规格mutable

​ mutable修饰符, 默认情况下Lambda函数总是一个const函数,mutable可以取消其常量性。在使用该修饰符时,参数列表不可省略(即使参数为空)。

#include <iostream>using namespace std;int main(){   int m = 0;   int n = 0;   [&, n] (int a) mutable { m = ++n + a; }(4);   cout << m << endl << n << endl;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.3.4 异常说明

​ 你可以使用 throw() 异常规范来指示 lambda 表达式不会引发任何异常。与普通函数一样,如果 lambda 表达式声明 C4297 异常规范且 lambda 体引发异常,Visual C++ 编译器将生成警告 throw() 。

int main() // C4297 expected {  	[]() throw() { throw 5; }(); }
  • 1
  • 2
  • 3
  • 4

在MSDN的异常规范 [5] 中,明确指出异常规范是在 C++11 中弃用的 C++ 语言功能。因此这里不建议不建议大家使用。

2.3.5 返回类型

​ Lambda表达式的返回类型会自动推导。除非你指定了返回类型,否则不必使用关键字。返回型类似于通常的方法或函数的返回型部分。但是,返回类型必须在参数列表之后,并且必须在返回类型->之前包含类型关键字。如果lambda主体仅包含一个return语句或该表达式未返回值,则可以省略Lambda表达式的return-type部分。如果lambda主体包含一个return语句,则编译器将从return表达式的类型中推断出return类型。否则,编译器将返回类型推导为void。

auto x1 = [](int i){ return i; };
  • 1

2.3.6 Lambda函数体

​ Lambda表达式的lambda主体(标准语法中的复合语句)可以包含普通方法或函数的主体可以包含的任何内容。普通函数和lambda表达式的主体都可以访问以下类型的变量:

- 捕获变量- 形参变量- 局部声明的变量- 类数据成员,当在类内声明**`this`**并被捕获时- 具有静态存储持续时间的任何变量,例如全局变量
  • 1
  • 2
  • 3
  • 4
  • 5
#include <iostream>using namespace std;int main(){   int m = 0;   int n = 0;   [&, n] (int a) mutable { m = ++n + a; }(4);   cout << m << endl << n << endl;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3.Lambda表达式的优缺点

3.1 Lambda表达式的优点

  • 可以直接在需要调用函数的位置定义短小精悍的函数,而不需要预先定义好函数

    std::find_if(v.begin(), v.end(), [](int& item){return item > 2});
    • 1
  • 使用Lamdba表达式变得更加紧凑,结构层次更加明显、代码可读性更好

3.2 Lambda表达式的缺点

  • Lamdba表达式语法比较灵活,增加了阅读代码的难度
  • 对于函数复用无能为力

4.Lambda表达式工作原理

4.1 Lambda表达式工作原理

​ 编译器会把一个lambda表达式生成一个匿名类的匿名对象,并在类中重载函数调用运算符,实现了一个operator()方法。

auto print = []{cout << "Hello World!" << endl; };
  • 1

​ 编译器会把上面这一句翻译为下面的代码:

class print_class{public:	void operator()(void) const	{		cout << "Hello World!" << endl;	}};//用构造的类创建对象,print此时就是一个函数对象auto print = print_class();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

4.2 C++仿函数

​ 仿函数(functor)又称为函数对象(function object)是一个能行使函数功能的类。仿函数的语法几乎和我们普通的函数调用一样,不过作为仿函数的类,都必须重载operator()运算符,仿函数与Lamdba表达式的作用是一致的。举个例子:

#include <iostream>#include <string>using namespace std; class Functor{public:    void operator() (const string& str) const    {        cout << str << endl;    }}; int main(){    Functor myFunctor;    myFunctor("Hello world!");    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

5.Lamdba表达式适用场景

5.1 Lamdba表达式应用于STL算法库

// for_each应用实例int a[4] = {11, 2, 33, 4};sort(a, a+4, [=](int x, int y) -> bool { return x%10 < y%10; } );for_each(a, a+4, [=](int x) { cout << x << " ";} );
  • 1
  • 2
  • 3
  • 4
// find_if应用实例int x = 5;int y = 10;deque<int> coll = { 1, 3, 19, 5, 13, 7, 11, 2, 17 };auto pos = find_if(coll.cbegin(), coll.cend(), [=](int i) {                     return i > x && i < y;});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
// remove_if应用实例std::vector<int> vec_data = {1, 2, 3, 4, 5, 6, 7, 8, 9};int x = 5;vec_data.erase(std::remove_if(vec.date.begin(), vec_data.end(), [](int i) {     return n < x;}), vec_data.end());std::for_each(vec.date.begin(), vec_data.end(), [](int i) {     std::cout << i << std::endl;});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

5.2 短小不需要复用函数场景

#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(void){    int data[6] = { 3, 4, 12, 2, 1, 6 };    vector<int> testdata;    testdata.insert(testdata.begin(), data, data + 6);    // 对于比较大小的逻辑,使用lamdba不需要在重新定义一个函数    sort(testdata.begin(), testdata.end(), [](int a, int b){         return a > b; });    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

5.3 Lamdba表达式应用于多线程场景

#include <iostream>#include <thread>#include <vector>#include <algorithm>int main(){    // vector 容器存储线程    std::vector<std::thread> workers;    for (int i = 0; i < 5; i++)     {        workers.push_back(std::thread([]()         {            std::cout << "thread function\";        }));    }    std::cout << "main thread\";    // 通过 for_each 循环每一个线程    // 第三个参数赋值一个task任务    // 符号'[]'会告诉编译器我们正在用一个匿名函数    // lambda函数将它的参数作为线程的引用t    // 然后一个一个的join    std::for_each(workers.begin(), workers.end(), [](std::thread &t;)     {        t.join();    });    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
std::mutex mutex;std::condition_variable condition;std::queue<std::string> queue_data;std::thread threadBody([&]{	std::unique_lock<std::mutex> lock_log(mutex);	condition.wait(lock_log, [&]{		return !queue_data.front();	});	std::cout << "queue data: " << queue_data.front();	lock_log.unlock();});queue_data.push("this is my data");condition.notity_one();if(threadBody.joinable()){	threadBody.join();}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

5.4 Lamdba表达式应用于函数指针与function

#include <iostream>#include <functional>using namespace std;int main(void){    int x = 8, y = 9;    auto add = [](int a, int b) { return a + b; };    std::function<int(int, int)> Add = [=](int a, int b) { return a + b; };    cout << "add: " << add(x, y) << endl;    cout << "Add: " << Add(x, y) << endl;    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

5.5 Lamdba表达式作为函数的入参

using FuncCallback = std::function<void(void)>;void DataCallback(FuncCallback callback){	std::cout << "Start FuncCallback!" << std::endl;	callback();	std::cout << "End FuncCallback!" << std::endl;}auto callback_handler = [&](){	std::cout << "This is callback_handler";};DataCallback(callback_handler);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

5.6 Lamdba表达式在QT中的应用

QTimer *timer=new QTimer;timer->start(1000);QObject::connect(timer,&QTimer::timeout,[&](){        qDebug() << "Lambda表达式";});
  • 1
  • 2
  • 3
  • 4
  • 5
int a = 10;QString str1 = "汉字博大精深";connect(pBtn4, &QPushButton::clicked, [=](bool checked){	qDebug() << a <<str1;	qDebug() << checked;	qDebug() << "Hua Windows Lambda Button";});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

6.总结

​ 对于Lambda这种新东西,有的人用的非常爽,而有的人看着都不爽。仁者见仁,智者见智。不管怎么样,作为程序员的你,都要会的。这篇文章就是用来弥补自己对C++ Lambda表达式的认知不足的总结,在很多开源代码中Lamdba表达式使用的非常多,如果不深入学习Lamdba相关知识,在未来学习开源代码就会有很多障碍。

timer->start(1000);QObject::connect(timer,&QTimer::timeout,[&](){        qDebug() << "Lambda表达式";});
  • 1
  • 2
  • 3
  • 4
int a = 10;QString str1 = "汉字博大精深";connect(pBtn4, &QPushButton::clicked, [=](bool checked){	qDebug() << a <<str1;	qDebug() << checked;	qDebug() << "Hua Windows Lambda Button";});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

6.总结

​ 对于Lambda这种新东西,有的人用的非常爽,而有的人看着都不爽。仁者见仁,智者见智。不管怎么样,作为程序员的你,都要会的。这篇文章就是用来弥补自己对C++ Lambda表达式的认知不足的总结,在很多开源代码中Lamdba表达式使用的非常多,如果不深入学习Lamdba相关知识,在未来学习开源代码就会有很多障碍。

网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发