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));
posted @ 2021-06-19 15:50  Onsunsl  阅读(104)  评论(0编辑  收藏  举报