我有两个大部分相同的方法,所以我正在考虑重构它们。
一个简单的版本是:
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
类型,然后执行参数。否则,您需要知道函数是否为 int
、void
、char
等,然后执行给定的参数。
关于c++ - 如何将函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29528617/