Lambda使用



1、Lambda的各種調用

void CTestA5::TestLambda()
{
    [](){cout << "call no param lambda" << endl; }();  // Lambda調用。無參數的情況
    auto testNoParam = [](){cout << "Assign and call no param lambda" << endl; }; // 賦值然後調用
    testNoParam();

    auto test = [](int k){ cout << "Assign and call param lambda, the param is :" << k << endl; }; // Lamada申明
    test(10); // 調用

    // 無參數但是有返回類型的調用
    auto test2 = []()->string{string strRet = "Return Value"; cout << "Assign and call return value lambda, the return is : " << strRet << endl; return strRet; };
    test2();

    // 非引用和引用調用,使用局部變量
    int offset = 10;
    int iOther = 100;
    function<int(int)> offsert_ByReference = [&](int j){return offset + j; };// 使用引用捕獲變量
    function<int(int)> offsert_ByValue = [=](int j){return offset + j; }; // 使用value捕獲變量
    offset = 20;

    function<int(int)> offsert_ByValueAndRef = [=, &iOther](int j){return offset + iOther + j + local_; }; // 部分複製,部分引用

    // 部分複製,部分引用,如果全部顯示指定,訪問this成員變量或則函數,需要增加this
    function<int(int)> offsert_ByValueAndRe2 = [this, offset, &iOther](int j){return offset + iOther + j + local_; };

    offset = 30;
    iOther = 1000;

    cout << "call lambda, use local variable, by value the value is " << offsert_ByValue(10) << endl;
    cout << "call lambda, use local variable, by reference the value is " << offsert_ByReference(10) << endl;
    cout << "call lambda, use local variable, by value and reference  is " << offsert_ByValueAndRef(10) << endl;

}
////////////////////////////////////////////////////////////////////////////////////////////////

2、不限制個數的模板參數
template<typename T, typename ...Arg>
class CTmpParam
{
public:
    int GetSizeof()
    {
        return sizeof...(Arg);
    }
    CTmpParam() = default;
    T t_;
    tuple<Arg...> tuple_;
};
void CTestA5::TestTmpParam()
{
    CTmpParam<int, float, double, string> CTst;
    int a = CTst.t_;
    float f1 = get<0>(CTst.tuple_);
    string str1 = get<2>(CTst.tuple_);

    int iSizeof = CTst.GetSizeof();
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章