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));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章