我正在尝试实现一种方法来处理C ++中的HTTP请求,但我遇到了一些微不足道的问题。我试图将函数封装到两个不同的类中,当我不知道如何在将回调函数实现为非静态成员函数时通过引用传递回调函数,是否有任何建议?
谢谢!
以下是我的一些实现:
// my_lib.hpp
#include <functional>
class my_lib {
public:
// A library to handle the HTTP requests
using request_callback = std::function<void(int response_code, const std::string &data)>;
void perform_request(std::string &url, std::string &body, const request_callback &callback);
};
// my_lib.cpp
#include "my_lib.hpp"
#include <string>
void my_lib::perform_request(std::string &url, std::string &body, const request_callback &callback) {
// Do http request...
std::string str("...");
callback(200, str);
}
// myClass.hpp
#include <string>
#include <functional>
#include "my_lib.hpp"
class myClass {
public:
using request_callback = std::function<void(int response_code, const std::string &data)>;
void on_action_callback(int response_code, const std::string &data);
void on_action_endpoint(const std::string &request, const request_callback &callback);
private:
my_lib* lib_instance;
};
// myClass.cpp
#include "myClass.hpp"
void myClass::on_action_callback(int response_code, const std::string &data) {
// do something
}
void myClass::on_action_endpoint(const std::string &request, const request_callback &callback) {
int code = 0;
// TODO: how should I pass the on_action_callback here....
lib_instance->perform_request("a.com", "a", myClass::on_action_callback);
}
答案 0 :(得分:0)
直接换成lambda:
lib_instance->perform_request("a.com", "a",
[this](int response_code, const std::string &data)
{ on_action_callback(response_code, data); });
此处this
应该被捕获以便能够调用成员函数。另一个选项是bind
this
,其中std::function
由您的成员函数构建,但您在这里并不需要这种复杂性