std::function与std::bind

  1. std::function 可调用对象的包装器,它是一个类模板,可以容纳函数指针,仿函数或可被转换为函数指针的类对象
    使用方法:在类型中填入函数签名(即函数类型,包括返回值和参数类型)
#include <iostream>
#include <functional>  // for std::function

void func(void)
{
    std::cout << __FUNCTION__ << std::endl;
}

class Foo
{
public:
    static int foo_func(int a)
    {
        std::cout << __FUNCTION__ << '(' << a << ") ->: ";     
        return a;
    }
};

class Bar
{
public:
    int operator()(int a)
    {
        std::cout << __FUNCTION__ << '(' << a << ')' << ") ->: ";   // __FUNCTION__可转换为该函数名字
        return a;
    }
};

int main(void)
{
    std::function<void(void)> fr1 = func;     // 绑定一个普通函数
    fr1();

    std::function<int(int)> fr2 = Foo::foo_func;   // 绑定一个类的静态成员函数
    std::cout << fr2(10) << std::endl;

    Bar bar;
    fr2 = bar;        // 绑定一个仿函数
    std::cout << fr2(20) << std::endl;

    using func_int_int = std::function<int(int)>;     // 通过using来定义函数指针类型
    func_int_int fr3 = Foo::foo_func;
    std::cout << fr3(30) << std::endl;

    return 0;
}

当要绑定一个类的普通成员函数(non-static)时,注意函数有个默认的第一个参数是类对象指针
访问一个类的普通成员函数时,不能class::function,因为non-static的函数不能直接访问,需要加&:&class::function

class Exp
{
public:
    Exp(int a) : m_a(a) { }
    int GetA() { return this->m_a; }
private:
    int m_a;
};

int main(void)
{
    std::function<int(Exp*)> fr4 = &Exp::GetA;   // 注意参数列表里有*Exp
    Exp a(40);
    std::cout << fr4(&a) << std::endl;    // 传入对象a的指针
}
  1. std::bind 绑定器:将一个可调用对象与一部分或全部的参数绑定起来,返回一个可调用对象,可用std::function接收,或使用auto。
    使用方法:std::bind(可调用对象, 参数列表)。参数列表可搭配std::placeholders占位符使用。
    注意调用顺序:bind括号内的参数顺序即实际调用的参数顺序,但是占位符的序号只是调用时第几个来取代自己,例如:
    std::bind(output, std:placeholders::_2, std::placeholders::_1)(1,2),实际调用是:output(2, 1), 因为_2是由参数的第二个来取代,_1是参数第一个来取代!!!
#include <iostream>
#include <functional>

void call_when_even(int x, const std::function<void(int)>& f)
{
    if (!(x & 1))
        f(x);
}

void func(int x)
{
    std::cout << x << std::endl;
}

int main(void)
{
    auto fr1 = std::bind(func, std::placeholders::_1);

    for (int i = 1; i <= 10; ++i)
        call_when_even(i, fr1);
}
#include <iostream>
#include <functional>

void output(int x, int y)
{
    std::cout << x << "  " << y << std::endl;
}

int main(void)
{
    std::bind(output, std::placeholders::_2, std::placeholders::_1)(1, 2);  // 输出2  1,注意顺序!!!
}
std::bind的组合应用:
auto f = std::bind(std::logical_and<bool>(), std::bind(std::greater<int>(), std::placeholders::_1, 5), std::bind(std::less<int>(), std::placeholders::_1, 10));
    for (int i = 0; i <= 13; ++i)
    {
        if (f(i))
            std::cout << i << std::endl;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值