【问题标题】:how to pass a member function with args as an argument to another member function?如何将带有 args 的成员函数作为参数传递给另一个成员函数?
【发布时间】:2015-04-23 09:27:14
【问题描述】:

以下示例适用于传递不带参数的成员函数指针。有人可以解释我如何用参数来做到这一点吗?如果可能的话,我们也可以传递可变数量的参数吗?

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));
}

【问题讨论】:

标签: c++ function-pointers member-function-pointers


【解决方案1】:

不,您只能在调用它时传递参数。如:

void test::mF1(check_fun_type ptr) {
    (this->*ptr)(2);
}

编辑

你可以使用std::bind来调用函数,它的一些参数是预先绑定到实参上的,例如:

test t1;
auto f = std::bind(&test::check2, &t1, 2);
f();

对于您的情况,您需要将test::mF1 的参数类型更改为std::function。如:

typedef std::function<void(test*)> check_fun_type;

void test::mF1(check_fun_type ptr) {
    ptr(this);
}

int main() {
    test t1;
    t1.mF1(std::bind(&test::check2, _1, 2));
}

DEMO

【讨论】:

  • bind 是一种 PITA,在大多数情况下,创建一个小的 lambda 包装器会更好。但是bind 确实回答了这个问题。除非你不说明结果不能作为实际的成员函数指针,需要把mF1的接口改成std::function
【解决方案2】:

在 C++11 中你可以使用

template <class F, class... Args>
void mFx(F ptr, Args... args)
{
    (this->*ptr)(args...);
}

传递任何类型的成员函数指针和可变数量的参数。
在 C++98 中,可以通过为每个数量的参数重载方法来实现类似的功能

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);
}

【讨论】:

  • 修复了格式,但我认为这并不是 OP 真正要求的。我相信他们想在调用站点修复参数,将使用 1 个参数调用的函数转换为没有调用的函数(模隐式 this)。
猜你喜欢
  • 2016-09-11
  • 2020-12-31
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 2018-09-18
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
相关资源
最近更新 更多