• c++ 11 lambda表达式


    #include <iostream>
    #include <typeinfo>
    #include <type_traits>
    #include <memory>
    #include <thread>
    #include <atomic>
    using namespace std;
    // lambda函数的语法定义:(采用了追踪返回类型的方式声明其返回值)
    // [capture](parameters) mutable -> return-type{statement;}
    // [],捕捉列表,捕捉上下文中的变量以供lambda函数使用
    /*[]    表示    空捕捉
     *[=]   表示值  传递方式捕捉所有父作用域的变量(包括this)
     *[&]   表示引用传递方式捕捉所有父作用域的变量(包括this)
     *[var] 表示值  传递方式捕捉变量var
     *[&var]表示引用传递方式捕捉变量var   
     *[this]表示值  传递方式捕捉当前this指针 (this。函数体内可以使用Lambda所在类中的成员变量。)
     *其它组合形式:
     * */
    class Test{
    public:
        Test(int a, int b): m_a(a),m_b(b){}
        void f1(int t){
            auto f = [this] {return m_a + m_b;}; // 省略参数列表,返回值由编译器推断为int
            cout <<__FILE__<< __LINE__ << "	"  << f() + t <<endl;
        }
        int m_a;
        int m_b;
    };
    
    int main()
    {
        [] {};  // 最简lambda函数
        int a = 3;
        int b = 4;
        // [=] 
        auto c = [=] {return a + b;}; // 省略参数列表,返回值由编译器推断为int
        cout <<__FILE__<< __LINE__ << "	"  << c() << endl;
        b ++;                         // 值捕捉注意: 它只捕捉一次。如需关联变量,用引用
        cout <<__FILE__<< __LINE__ << "	"  << c() << endl;
        // [&]
        auto d = [&] {return a + b;}; // 省略参数列表,返回值由编译器推断为int
        cout <<__FILE__<< __LINE__ << "	"  << d() << endl;
        b ++;                         // 值捕捉注意: 它只捕捉一次。如需关联变量,用引用
        cout <<__FILE__<< __LINE__ << "	" << d() << endl;
        // [this]
        Test t(1,2);
        t.f1(9);
        return 0;
    }
    

      

  • 相关阅读:
    刚学的 activity 之间的两种(带数据)跳转
    SharePreference 把少量数据写到 文件中
    Android 使用资源
    SQLite 初步测试
    android 操作 sd 卡上的文件
    android 操作文件
    002android 布局(layout)
    Activity_liftCycle — 生命周期
    android 创建、删除 文件和文件夹 测试
    android 实现粗糙的文件浏览器
  • 原文地址:https://www.cnblogs.com/freebird92/p/9732850.html
Copyright © 2020-2023  润新知