#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;
}
第13章 网络 13.6.3 实现多样化回调 02用模板实现更强大的回调 绑定函数对象
于 2023-11-27 19:15:05 首次发布