c++ bind/packaged_task/forward

1 bind

在C++中,std::bind是一个功能强大的工具,定义在 <functional> 头文件中,它允许你绑定一个可调用对象(如函数、函数对象或Lambda表达式)到特定的参数,并生成一个新的可调用对象。这个新的可调用对象在调用时会调用原始的可调用对象,并传递给它绑定的参数。

签名函数

template< class F, class... Args >
constexpr /*unspecified*/ bind( F&& f, Args&&... args );

std::bind的意义和用途主要体现在以下几个方面:

  1. 参数绑定:你可以使用std::bind来固定一个或多个函数的参数。这样,当你调用绑定后的函数时,就不需要再传递这些已经固定的参数。
  2. 回调和事件处理:在编程中,经常需要将一个函数作为另一个函数的参数传递,以便在某个事件发生时调用它。std::bind可以帮助你创建这样的回调函数,它可以携带额外的上下文信息。
  3. 适配器std::bind可以作为一个适配器,将不兼容的函数签名转换为兼容的签名。这对于需要特定签名的API或回调函数特别有用。
  4. 延迟执行:通过std::bind,你可以创建一个可调用对象,该对象封装了某个函数及其参数,但并不会立即执行。你可以将这个可调用对象存储起来,并在需要的时候调用它。
#include <iostream>  
#include <functional>  
  
void print_sum(int a, int b, int c) {  
    std::cout << a + b + c << std::endl;  
}  
  
int main() {  
    // 使用std::bind绑定print_sum函数的前两个参数为10和20  
    auto bound_func = std::bind(print_sum, 10, 20, std::placeholders::_1);  
      
    // 调用bound_func时,只需要传递一个参数(即print_sum的第三个参数)  
    bound_func(30);  // 输出60,因为10 + 20 + 30 = 60  
      
    return 0;  
}

 除了 std::bind 函数外,C++11 还提供了一个新的语言特性——Lambda 表达式,可以用来替代 std::bind 函数。Lambda 表达式可以更加灵活地实现函数对象的绑定和参数传递。例如:

auto add = [](int x) { return add(9, x); };
std::cout << add(6) << std::endl; // 输出 15

2 forword

std::forward 是 C++11 引入的一个模板函数,它用于完美转发(Perfect Forwarding)函数参数。完美转发意味着将参数按照它们原来的类型(包括值类别,即左值或右值)转发给另一个函数。

template<class T>  
T&& forward(typename std::remove_reference<T>::type& t);

int&& club(int&& a)
{
	//int temp = 4;
	return std::forward<int>(a);//因为返回类型为引用,返回值不会创建一个零时对象也就不会调用构造函数
}
int main()
{
	cout<<club(4);
	return 0;
 
}

 使用 std::forward 时,通常与模板函数和完美转发一起使用,以便将参数按照它们原来的值类别转发给另一个函数。这在编写通用包装器或代理函数时特别有用,比如 std::bindstd::thread 的构造函数、lambda 表达式或者自定义的转发函数。

 /* 
    * unused.
    *
    * @brief 用线程池启用任务(F是function, Args是参数) 
    * @param 超时时间 ,单位ms (为0时不做超时控制) ;若任务超时,此任务将被丢弃 
    * @param bind function 
    * @return 返回任务的future对象, 可以通过这个对象来获取返回值 
    *
    * template <class F, class... Args> 
    * 它是c++里新增的最强大的特性之一,它对参数进行了高度泛化,它能表示0到任意个数、任意类型的参数 
    * auto exec(F &&f, Args &&... args) -> std::future<decltype(f(args...))> 
    * std::future<decltype(f(args...))>:返回future,调用者可以通过future获取返回值 
    * 返回值后置
    */
    template<class F,class... Args>
    auto exec(int64_t timeoutMs,F&& f,Args&&... args) -> future<decltype(f(args...))>
    {
        //获取现在时间
        int64_t expireTime=(timeoutMs==0)?0:TNOWMS+timeoutMs;
        // 定义返回值类型
        using retType=decltype(f(args...));
        // 封装任务
        auto task=make_shared<packaged_task<retType()>>(bind(forward<F>(f),forward<Args>(args)...));
        // 封装任务指针,设置过期时间
        TaskFuncPtr fPtr=make_shared<TaskFunc>(expireTime);
        fPtr->_func=[task](){
            (*task)();
        };

        unique_lock<mutex> lock(_mutex);
        // 插入任务
        _tasks.push(fPtr);
        // 唤醒阻塞的线程,可以考虑只有任务队列为空的情 况再去notify
        _condition.notify_one();

        return task->get_future();
    }

packaged_task 

std::packaged_task 是 C++ 标准库中的一个模板类,它用于包装一个可调用对象(比如函数、lambda 表达式或函数对象),以便可以异步执行该对象,并获取其返回值。std::packaged_task 常常与 std::future 和 std::async 一起使用,以支持异步编程。

template<class R, class ...Args>
class packaged_task<R(Args...)>;
 

#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <chrono>
#include <future>

using namespace std;
//普通函数
int Add(int x, int y)
{
    return x + y;
}


void task_lambda()
{
    //包装可调用目标时lambda
    packaged_task<int(int,int)> task([](int a, int b){ return a + b;});
    
    //仿函数形式,启动任务
    task(2, 10);
    
    //获取共享状态中的值,直到ready才能返回结果或者异常
    future<int> result = task.get_future();
    cout << "task_lambda :" << result.get() << "\n";
}

void task_thread()
{
    //包装普通函数
    std::packaged_task<int (int,int)> task(Add);
    future<int> result = task.get_future();
    //启动任务,非异步
    task(4,8);
    cout << "task_thread :" << result.get() << "\n";
        
    //重置共享状态
    task.reset();
    result = task.get_future();

    //通过线程启动任务,异步启动
    thread td(move(task), 2, 10);
    td.join();
    //获取执行结果
    cout << "task_thread :" << result.get() << "\n";
}

int main(int argc, char *argv[])
{
    task_lambda();
    task_thread();

    return 0;
}

 参考:

C++11之packaged_task使用介绍-CSDN博客

  • 17
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值