C++11學習筆記之三lamda表達式,std::function, std::bind


//lamda
//first lamda
[]
{};

// second lamda
[]() //or no need () when paramater is null
{
std::cout << "second" << std::endl;
}();// last add(), express will call this lamda func

// 3 with return type
auto kkk = []()
{
return 1;
}();

// 4, set return type
auto kkkk = [] (int i) -> bool { return (bool)i; }(5);

//5, lamda capture, [=], [=,&], [&], [this][] 不捕獲...
/*[&] 以引用的方式捕獲
[=] 通過變量的一個拷貝捕獲
[=, &foo] 通過變量的拷貝捕獲,但是用foo變量的引用捕獲
[bar] 通過復制捕獲,不要復制其他
[this] 捕獲this指針對應成員
*/

 

 

function, bind等,上代碼

#include <iostream>
#include <functional>
using namespace std;
typedef std::function<void()> fp;
typedef std::function<void(int)> fpi1;
void g_fun()
{
    std::cout << "global function bind" << std::endl;
}

class A
{
public:
    static void aFunStatic()
    {
        std::cout << "aFunStatic" << std::endl;
    }

    virtual void aFun()
    {
        std::cout << "aFun" << std::endl;
    }

    void aFunI1(int i)
    {
        std::cout << "aFunI1:"  << i << std::endl;
    }

};

class DerivedA
    :public A
{
public:
    virtual void aFun() override
    {
        std::cout << "aFun in DeriveA" << std::endl;
    }
};

class B
{
public:
    void bCallAFun()
    {
        if(callFun)
            callFun();
    }
    void bCallAFunStatic()
    {
        if(callFunStatic)
            callFunStatic();
    }

    void bCallAFunI1(int i)
    {
        if(callFunI1)
            callFunI1(i);
    }

    fp callFunStatic;
    fp callFun;
    fpi1 callFunI1;
};


void main()
{
    B b;
    A a;

    //bind to global function
    fp f = fp(&g_fun);
    f();

    //bind to class function
    //static
    b.callFunStatic = std::bind(&A::aFunStatic);
    b.bCallAFunStatic();

    //no static function without parameter
    b.callFun = std::bind(&A::aFun, &a);
    b.bCallAFun();

    //no static function with parameter
    b.callFunI1 = std::bind(&A::aFunI1, &a, std::placeholders::_1);
    b.bCallAFunI1(5);

    //about polymorphic
    DerivedA da;
    b.callFun = std::bind(&A::aFun, &da);
    b.bCallAFun();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM