第13章 网络 13.6.3 实现多样化回调 02用模板实现更强大的回调 绑定函数对象

#include <curl/curl.h>
#include <iostream>
#include <fstream>
#include <string>
#include <functional>

using namespace std;

struct CURLFunctionHelper
{
    CURLFunctionHelper(CURL* curl, CURLoption opt_function, CURLoption opt_data)
    {
        curl_easy_setopt(curl, opt_function, inner_function);
        curl_easy_setopt(curl, opt_data, this);
    }

    template <typename Fn>

    void Bind(Fn&& fn) //参数类型为右值
    {
        _callback = std::move(fn);//转移
    }

private:
    //简化function类型表达
    typedef std::function <size_t(char*, size_t, size_t)> CURLCallback;
    //负责转接的静态成员函数
    static size_t inner_function(char* data
                                 , size_t size, size_t nmemb
                                 , void* userdata)
    {
        auto self = static_cast <CURLFunctionHelper*> (userdata);
        return self->_callback(data, size, nmemb); //在此处转发
    }

    //function<>成员
    CURLCallback _callback;
};

struct StdOutputer
{
    size_t operator()(char* data, size_t size, size_t nmemb)
    {
        std::string line(data, size*nmemb);
        cout << line ;
        return size*nmemb;
    }
};

int main()
{
    curl_global_init(CURL_GLOBAL_DEFAULT);
    CURL* handle = curl_easy_init();
    string url = "ftp://d2school:123456@127.0.0.1/:21";
    curl_easy_setopt(handle, CURLOPT_URL, url.c_str());

    CURLFunctionHelper helper(handle, CURLOPT_HEADERFUNCTION, CURLOPT_HEADERDATA);

    //绑定一个函数对象,注意它的入参和返回值
    StdOutputer outputer;
    helper.Bind(outputer);

    curl_easy_perform(handle);
    curl_easy_cleanup(handle);
    curl_global_cleanup();
    return 0;
}

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值