I'm trying to pass a function pointer as a parameter of another function, but the function pointer may or may not itself have an argument (making it different from the other questions I searched for).
The code works as is, but MY problem is that I was trying to use a single function and pass in each different function pointer, but what I have below is 3 different functions to pass each function pointer. I'd like to get rid of the 3 different function definitions as they are all the same with the exception of the passed in function pointer (so basically, 3 copies of execute_func() definitions). Here's what I have so far but this doesn't seem right that I should need three execute_func() calls.
class A { ... };
class B { ... };
class Test {
private:
std::function<void()> fp;
std::function<void(MyA &)> fp;
std::function<void(MyB &)> fp;
// ...
};
// Here I create a function pointer for each of my calls.
Test::Test() {
fp = std::bind(&Test::do_this, this);
fp_a = std::bind(&Test::do_a, this, std::placeholders::_1);
fp_b = std::bind(&Test::do_b, this, std::placeholders::_1);
}
// Here my intention was to have only 1 execute_func() call and I would
// pass in the pointer to the function that I want to call.
Test::test_it()
{
A a;
B b;
execute_func(fp);
execute_func(fp_a, a);
execute_func(fp_b, b);
}
// I was hoping to only need one function, but so far
// have needed 3 functions with diff signatures to make it work.
bool Test::execute_func(std::function<void()> fp) {
// ... more code here before the fp call
fp();
// ... them more common code here.
}
bool Test::execute_func(std::function<void(MyA &)> fp, MyA &a) {
// ... more common code here
fp(a);
// ... and more common code here
}
bool Test::execute_func(std::function<void(MyB &)> fp, MyB &b) {
// ... more common code here
fp(b);
// ... and more common code here.
}
// And of course the execute_func() calls call these members as passed in.
bool Test::do_this() { ... }
bool Test::do_a(MyA &a) { ... }
bool Test::do_b(MyB &b) { ... }
Thoughts on where I'm going wrong?