c++ 的bin 與lambda 實現函式引數繫結
阿新 • • 發佈:2021-06-19
用過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