I have a class Alpha
and a function pointFun
which should accept both Alpha
member functions and generic external functions (e.g.: defined in the main).
I have overridden pointFun
to make it useable both by Alpha
member functions and by external functions. But since pointFun
function is actually very long I want to avoid to repeat it twice.
Is there a way to accept both function pointer types? I tried to do that (see the commented part of code) but it doesn't work.
// fpointer.h
#include <iostream>
using std::cout;
using std::endl;
class Alpha {
public:
Alpha() {}
void pointFun (void (Alpha::*fun)());
void pointFun (void (*fun)());
//void pointFun (void (*funA)(), void (Alpha::*funB)()); // <-- how to make THIS instead of the previous two?
void printA ();
void assignF ();
private:
int value;
bool set;
};
void Alpha::pointFun(void (Alpha::*fun)()) {
(Alpha().*fun)();
}
void Alpha::pointFun(void (*fun)()) {
(*fun)();
}
/* // I want this:
void Alpha::pointFun(void (*funA)() = 0, void (Alpha::*funB)() = 0) {
(*funA)();
(Alpha().*funB)();
// same code, different pointer functions
}
*/
void Alpha::printA() {
cout << "A" << endl;
// some long code
}
void Alpha::assignF () {
pointFun(&Alpha::printA);
}
And this is the main:
// MAIN.cpp
#include <iostream>
#include "fpointer.h"
using namespace std;
void printB() {
cout << "B" << endl;
// same long code as before
}
int main() {
Alpha A;
A.pointFun(printB);
A.assignF();
}