• 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));
    
  • 相关阅读:
    51Nod 1006 最长公共子序列Lcs
    输入和输出
    51Nod 1092 回文字符串
    51Nod 1050 循环数组最大子段和
    项目初始
    一元多项式求导 (25)
    说反话 (20)
    数组元素循环右移问题 (20)
    素数对猜想 (20)
    换个格式输出整数 (15)
  • 原文地址:https://www.cnblogs.com/onsunsl/p/14903141.html
Copyright © 2020-2023  润新知