【施磊C++】bind绑定器和function函数对象


前言

本文介绍了bind绑定器和function函数对象,基于施磊老师的C++课程。


一、模板的完全特例化和部分特例化

还有模板的实参推演,这里省略。

二、function的实现原理

function的实现本质上就是定义了一个类首先接收函数指针类型,然后封装了一个()运算符重载函数,在这个运算符重载函数中对之前接收的函数指针进行调用。这是基于模板的实参推演,而为了推演任意的函数,使用了可变参模板:

#include <iostream>
#include <string>
using namespace std;

template<typename T>
class myfunction {};

template<typename R, typename... args>
class myfunction<R(args...)>
{
public:
    using PFUNC = R(*)(args...);
    myfunction(PFUNC p) : pfunc(p) {}
    R operator() (args... arg) {
        return pfunc(arg...);
    }
private:
    PFUNC pfunc;
};

int sum(int a, int b) {
    return a + b;
}

void hello(string str) {
    cout << str << endl;
}

int main()
{
    myfunction<void(string)> f(hello);
    f("hello world!");
    myfunction<int(int, int)> p(sum);
    cout << p(10, 20) << endl;

    return 0;
}

注意需要先定义一个类模板,在通过模板的特例化定义带有参数的版本。

三、bind和function实现线程池

bind返回的也是函数对象,注意参数占位符的运用:
在这里插入图片描述

下面使用bind和function实现的线程池:

#include <iostream>
#include <functional>
#include <vector>
#include <thread>
using namespace std;

class Thread
{
public:
    Thread(function<void()> func) : _func(func) {}
    thread start() {
        thread t(_func);
        return t;
    }
private:
    function<void()> _func;
};

class ThreadPool
{
public:
    ThreadPool() {}
    ~ThreadPool() {
        for (int i = 0; i < _pool.size(); i++) {
            delete _pool[i];
        }
    }
    void startPool(int size)
    {
        for (int i = 0; i < size; i++) {
            _pool.push_back(new Thread(bind(&ThreadPool::runInThread, this, i)));
        }
        for (int i = 0; i < size; i++) {
            _handler.push_back(_pool[i]->start());
        }
        for (thread &t : _handler) {
            t.join();
        }
    }
private:
    vector<Thread*> _pool;
    vector<thread> _handler;
    void runInThread(int id) {
        cout << "call runInThread id: " << id << endl;
    }
};

int main()
{
    ThreadPool pool;
    pool.startPool(10);

    return 0;
}

四、lambda表达式的实现原理

lambda表达式本质就是函数对象的简化版本
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值