How can I pass a member function with args as an argument to another member function?
The following example works by passing a member function pointer with no arguments. Can anyone explain to me how to do this with arguments? If possible, can we also pass a variable number of arguments?
class test {
public:
typedef void (test::*check_fun_type)();
//typedef void (test::*check_fun_type)(int);
void mF1(check_fun_type ptr);
void check1();
void check2(int v1);
};
void test::check1() {
std::cout << "check1" << std::endl;
}
void test::check2(int v1) {
std::cout << "check2 " << v1 << std::endl;
}
void test::mF1(check_fun_type ptr) {
(this->*ptr)();
}
int main() {
test t1;
t1.check1();
t1.check2(2);
t1.mF1(&test::check1);
//t1.mF1((&test::check2)(2));
}
source to share
No, you can only pass arguments when called. For example:
void test::mF1(check_fun_type ptr) {
(this->*ptr)(2);
}
EDIT
You can use std::bind
to call a function with some of its parameters associated with the arguments in advance, for example:
test t1;
auto f = std::bind(&test::check2, &t1, 2);
f();
For your case, you need to change the parameter type test::mF1
to std::function
. For example:
typedef std::function<void(test*)> check_fun_type;
and
void test::mF1(check_fun_type ptr) {
ptr(this);
}
int main() {
test t1;
t1.mF1(std::bind(&test::check2, _1, 2));
}
source to share
In C ++ 11, you can use
template <class F, class... Args>
void mFx(F ptr, Args... args)
{
(this->*ptr)(args...);
}
pass a pointer to a member function of any type and a variable number of arguments.
In C ++ 98, similar functionality can be achieved with overloading methods for each number of arguments
template <class F>
void mFx(F ptr)
{
(this->*ptr)();
}
template <class F, class A1>
void mFx(F ptr, A1 a1)
{
(this->*ptr)(a1);
}
template <class F, class A1, class A2>
void mFx(F ptr, A1 a1, A2 a2)
{
(this->*ptr)(a1, a2);
}
source to share