c++ - 如何将函数作为参数传递

标签 c++ function-pointers

我有两个大部分相同的方法,所以我正在考虑重构它们。

一个简单的版本是:

void C::GetEmailAlerts(set<AlertPtr>& alertSet)
{
  ...
  ... 
  AlertPtr pAlert = Cache::Get()->GetAlert();
  for (...) {
    ...
    if (pAlert->isEmail())
      alertSet.insert(p);
  }
  ...
}

void C::GetMobileAlerts(set<AlertPtr>& alertSet)
{
  ...
  ... 
  AlertPtr pAlert = Cache::Get()->GetAlert();
  for (...) {
    ...
    if (pAlert->isMobile())
      alertSet.insert(p);
  }
  ...
}

有没有可能让它变成这样:

void C::GetAlerts(set<AlertPtr>& alertSet, ??? func) // How to pass a function as parameter?
{
  ...
  ... 
  AlertPtr pAlert = Cache::Get()->GetAlert();
  for (...) {
    ...
    if (pAlert->func())
      alertSet.insert(p);
  }
  ...
}

这样我就可以调用:

C c;
c.GetAlerts(emailSet, isEmail);
c.GetAlerts(mobileSet, isMobile);

------------------------编辑-------------------- -

也许一个通用的例子更容易展示我想要的东西:

#include <iostream>
using namespace std;

struct A
{
    int foo() { cout<<"in foo()"<<endl; }
    int bar() { cout<<"in bar()"<<endl; }
};

A *instance = new A();

struct C
{
public:
  void test1()
  {
    instance->foo();
  }
  void test2()
  {
    instance->bar();
  }

//  void test(???) // How to pass member function as a pointer?
//  {
//    instance->f();
//  }
};

int main()
{
  C c;
  c.test1();
  c.test2();

//  c.test(&A::foo);
//  c.test(&A::bar);

  return 0;
}

在第二个示例中,我想使用 c.test(&A::foo); 来替换 c.test1(),也许还有 c。 test2, c.test3, ...

有没有一种干净的方法来做到这一点?

最佳答案

嗯,视情况而定。如果你使用的是C++11,你可以使用auto类型,然后执行参数。否则,您需要知道函数是否为 intvoidchar 等,然后执行给定的参数。

关于c++ - 如何将函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29528617/

相关文章:

c++ - 如何将类方法转换为 QScriptEngine::FunctionSignature

c++ - 打印到 Windows 控制台度数 (°) 和立方体符号 (³)

c++ - std::basic_string 特化

c++ - 模板警告和错误帮助,(gcc)

c# - 如何跨不同的编程语言共享业务概念?

c - 为什么 `p()` 和 `(*p)()` 都有效?

methods - 在 Python 3 中将方法分配给 var 时如何自动使用 self currying?

c++ - 如何设置QTreeView的起点目录?

c++ - 仅在运行时给出签名时的函数指针调用

c - 定义一个包含函数指针的结构,该函数指针指向以该结构作为参数的函数