I need to solve such a problem. There is a base class and two inherited classes. The base class contains method which needs a function-pointer as a parameter. But such functions are defined in inherited classes.
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 compiler gives an error on WaitEvent calls:
error C2664: 'CBase::WaitEvent' : cannot convert parameter 1 from 'bool (__thiscall CChildA::* )(void)' to 'FPredicate'
A question is: how shall I change the code to make it work? will it be safe to rewrite WaitEvent call as
WaitEvent((FPredicate)(&CChildA::a1), 100)
?
In this case compiler tells of no error but is it safe? Or is there a better way of solving a problem?
Thank you in advance.
bind()
should already be instd::
. And it's generally beneficial to use -std=c++0x, as some little features, that help in everyday programming, are usable already. – Griwes Mar 29 '12 at 9:31