zoukankan      html  css  js  c++  java
  • c++ 的bin 与lambda 实现函数参数绑定

    用过python 的同学都知道 functools.partial 和 lambda 可以实现绑定, 这在线程池调用很有用。
    下面看看C++ 与python 的实现对比

    #include <iostream>
    #include <functional>
    
    int fun(int a, int b, int c)
    {
     std::cout << a << " " << b << " " << c << std::endl;
     return a;
    }
    
    int main(int argc, char *argv[])
    {
        auto foo = std::bind(fun, 1, std::placeholders::_1, std::placeholders::_2);
        foo(2, 3);
    
        auto bar = std::bind(fun, 1, std::placeholders::_2, std::placeholders::_1);
        bar(2, 3);
    
        int a = 1;
        auto bar2 = [=](int b, int c)
        {
            std::cout << a << " " << b << " " << c << std::endl;
        };
        bar2(2, 3);
        bar2(3, 2);
    
        return 0;
    }
    
    
    from functools import partial
    
    
    def fun(a, b, c):
        print(a, b, c)
    
    
    foo = partial(fun, 1)
    
    foo(2, 3)
    bar = foo
    bar(3, 2)
    
    x = 1
    bar1 = lambda b, c: print(x, b, c)
    bar(2, 3)
    bar(3, 2)
    
    
    

    输出log都一样

    1 2 3
    1 3 2
    1 2 3
    1 3 2
    

    如果函数是引用的话需要加std::ref, 而常量引用使用std:cref

    void fun(int& a)
    {
    }
    
    int a;
    audo foo = std::bind(std::ref(a));
    
  • 相关阅读:
    延迟消失菜单
    控制产品上下滚动
    百度音乐全选
    百度文库评分两种代码写法
    选项卡
    搜狐视频
    m 调用传参图片切换
    IIS 7.5站点配置
    jquery plugins —— datatables 搜索后汇总
    jquery plugins —— datatables 增加行号
  • 原文地址:https://www.cnblogs.com/onsunsl/p/14903141.html
Copyright © 2011-2022 走看看