Reputation: 21
I have the following:
class NetRequest: public QObject {
Q_OBJECT
public:
NetRequest(QString postData, void(BrowserApp::*f)(QByteArray));
QString postData;
void (BrowserApp::*fn)(QByteArray);
public slots:
void requestFinished(QNetworkReply *r);
}
and the cpp is:
NetRequest::NetRequest(QString postData, void(BrowserApp::*f)(QByteArray)) {
this->postData = postData;
this->fn = f;
}
void NetRequest::requestFinished(QNetworkReply *r) {
QByteArray data;
fn(data);<--- this doesn't work
}
I am trying to call the function "fn" in requestFinished but the compiler doesn't let me - what am I please doing wrong?
Thank you for all your help!
Upvotes: 0
Views: 74
Reputation: 101456
When you have a pointer-to-member-function, in order to call through it you must also have a pointer to the object you are using for the call.
But your code:
fn(data);
Has no such object pointer. You probably are assuming that an object is associated with the member function pointer -- but it isn't.
Try this:
(that->*fn)(data);
that
is a pointer to a BrowserApp
object. It will need to be either passed in to the requestFinished
function, or somehow stored in the NetRequest
object -- probably at the same time when fn
is set.
Upvotes: 2
Reputation: 409176
I suggest you look into std::function
and std::bind
. They will help you in many ways when it comes to "function pointers".
Then it would look something like this instead:
class NetRequest: public QObject {
std::function<void(QByteArray)> fn;
// ...
public:
NetRequest::NetRequest(QString postData, std::function<void(QByteArray)> f) {
// ...
fn = f;
}
// ...
};
Now when creating an instance of the NetRequest
object, you must use std::bind
to bind a function from the BrowserApp
class to the std::function
object:
BrowserApp app;
NetRequest request("some string", std::bind(&BrowserApp::SomeFunction, app));
The nice thing about using std::function
is that the callback function no longer have to be a BrowserApp
member function, it can by any function, including lambda expressions.
Upvotes: 0