Reputation: 115
I have this code:
#ifndef FUNCSTARTER_H
#define FUNCSTARTER_H
#endif // FUNCSTARTER_H
#include <QObject>
class FunctionStarter : public QObject
{
Q_OBJECT
public:
FunctionStarter() {}
virtual ~FunctionStarter() {}
public slots:
void FuncStart(start) {
Start the function
}
};
In the FuncStart function, you would put your function in as a parameter and then it would execute the parameter (aka the function). How would I do this?
Upvotes: 2
Views: 135
Reputation: 143795
either you pass a function pointer, or you define a functor class. A functor class is a class that overloads operator(). This way, the class instance becomes callable as a function.
#include <iostream>
using namespace std;
class Functor {
public:
void operator()(void) {
cout << "functor called" << endl;
}
};
class Executor {
public:
void execute(Functor functor) {
functor();
};
};
int main() {
Functor f;
Executor e;
e.execute(f);
}
Upvotes: 3
Reputation: 258608
You'd pass the function pointer as parameter. This is called a callback.
typedef void(*FunPtr)(); //provide a friendly name for the type
class FunctionStarter : public QObject
{
public:
void FuncStart(FunPtr) { //takes a function pointer as parameter
FunPtr(); //invoke the function
}
};
void foo();
int main()
{
FunctionStarter fs;
fs.FuncStart(&foo); //pass the pointer to the function as parameter
//in C++, the & is optional, put here for clarity
}
Upvotes: 2