【发布时间】:2012-04-12 22:10:07
【问题描述】:
我需要解决这样的问题。 有一个基类和两个继承类。基类包含需要函数指针作为参数的方法。但是这样的函数是在继承的类中定义的。
class CBase;
typedef bool (CBase::*FPredicate)();
class CBase
{
public:
CBase() {}
~CBase() {}
protected:
//this method waits until 'predicate' is true or until 'timeout' ms. passed
//and returns true if 'predicate' is true eventually
bool WaitEvent(FPredicate predicate, int timeout)
{
bool result = false;
int time1 = GetTickCount();
int time2;
bool isEnd = false;
while(!isEnd)
{
result = isEnd = (this->*predicate)();
time2 = GetTickCount();
if(time2 - time1 > timeout && !isEnd)
isEnd = true;
}
return result;
}
};
class CChildA : public CBase
{
protected:
bool a1() {/*some work*/}
bool a2() {/*some work*/}
void a_main()
{
...
WaitEvent(&CChildA::a1, 100);
...
WaitEvent(&CChildA::a2, 100);
...
}
};
class CChildB : public CBase
{
protected:
bool b1() {/*some work*/}
bool b2() {/*some work*/}
void b_main()
{
...
WaitEvent(&CChildB::b1, 100);
...
WaitEvent(&CChildB::b2, 100);
...
}
};
MSVC 2005 编译器在调用 WaitEvent 时出错:
错误 C2664: 'CBase::WaitEvent' : 无法将参数 1 从 'bool (__thiscall CChildA::* )(void)' 转换为 'FPredicate'
一个问题是:我应该如何更改代码以使其工作?将 WaitEvent 调用重写为是否安全
WaitEvent((FPredicate)(&CChildA::a1), 100)?
在这种情况下,编译器不会报告任何错误,但它安全吗?或者有没有更好的解决问题的方法?
提前谢谢你。
【问题讨论】:
-
有没有机会使用 boost 或 std::tr1?在这种情况下,您只需使用函数
并在派生类中使用带有成员函数的bind() -
@stijn,记住,C++11 已经上线,
bind()应该已经在std::中了。使用 -std=c++0x 通常是有益的,因为一些有助于日常编程的小功能已经可用。 -
你能把派生类中的可调用函数从基类虚拟化吗?
-
不幸的是,我从未使用过 boost,我不想使用整个大型新库来解决这个问题。
-
@Griwes 是的,但操作没有标记 C++11,我认为 SO 的一般规则是,如果你想要 C++11,你应该这样标记?
标签: c++ inheritance member-function-pointers