The following example works with passing a member function pointer with no arguments. Can someone explain me how to do this with arguments? If it is possible can we also pass 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));
}
No, you can only pass the arguments when calling it. Such as:
void test::mF1(check_fun_type ptr) {
(this->*ptr)(2);
}
EDIT
You can use std::bind
to invoke function with some of its parameters bound to arguments in advance, such as:
test t1;
auto f = std::bind(&test::check2, &t1, 2);
f();
For your case, you need to change the parameter type of test::mF1
to std::function
. Such as:
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));
}
In C++11 you could use
template <class F, class... Args>
void mFx(F ptr, Args... args)
{
(this->*ptr)(args...);
}
to pass member function pointer of any type and variable number of arguments.
In C++98 similar functionality can be achieved by 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.