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();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值