函数指针和lambda

函数指针:

函数指针定义
1.auto
2.function<>

闭包:

闭包是带有上下文的函数,说白了,就是有状态的函数
一个函数带上了状态就形成了闭包
函数是代码,状态是一组变量
闭包的状态·捆绑,必须发生在运行时
实现:
1.使用类重载()运算符定义函数对象
2.用C++11的bind函数实现闭包
3.用c++11的lambda表达式实现闭包

lambda:

定义:
[capture] (parameters) mutable return-type{
statement;//可以做类型推导
};
值传递方式
[var]:值捕获
【=】所有父作用域的变量
【this】this 指针
引用传递方式:
【&var】引用捕获
【&】所有父作用域的变量

#include<iostream>
using namespace std;
struct Print{
    static void print(int n){
        cout<<"class static  ---- n ="<<n<<endl;
    }
    void print2(int n){
        cout<<"class number ---- n ="<<n<<endl;
    }
    void printLamba(const std::vector<int >arr,){
        cout<<"class number ---- n ="<<n<<endl;
    }
}
void helloworld(){
    cout<<"hello world"<<endl;
}
int main(){
    auto func=helloworld;
    auto ap1=&Print::print;
    ap1(123);
    Print obj;
    //void (Print::*ap2)(int)=&Print::print;
    // auto ap2=&Print::print2;
    // (obj.*ap2)(123);
    std::vector<int>arr;
    arr.push_back(1);
    arr.push_back(2);
    int m=3;
    cout<<"begin m="<<m<<endl;
    cout<<"origin address of m="<<&m<<endl;
    obj.print2(arr,[&m](int n)mutable{
        Point p;
        int mm=1;
        mm++;
        m++;
        cout<<"address of m ="<<&m<<" m ="<<m<<endl;
        cout<<"address of mm ="<<&mm<<" mm ="<<mm<<endl;
        cout<<"print with lambda =n*2"<<endl;

    });
    cout<<"end m ="<<m<<endl;
    func();
}
//嵌套使用lambda
#include<iostream>
auto functionA=[](int n){
    std::cout<<"functionA"<<std::endl;
};
auto functionB=[](int n){
    functionA(n);
};
auto ADD=[](int a,int b){
    return a+b;
};

auto SUB=[](int a,int b){
    return a-b;
};
auto MAX=[](int a,int b){
    return a>b?a:b;
};
auto MIN=[](int a,int b){
    return a<b?a:b;
};
struct Data{
private:
    int a,b;
public:
     Date(int m,int n):a(m),b(n){
         
     }
     int operator()(std::function<int(int,int)>func){
          return func(a,b);
     }
};

auto Data2=[](int&&a,int&&b){
    return [&](std::function<int(int,int)>func){
        return func(a,b);
    };
};
int main(){
    functionB(123);
    auto data=Data(1,2);
    data(ADD);
    data(SUB);
    data(MAX);
    data(MIN);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值