成员函数指针和继承

Ole*_*nov 9 c++ inheritance member-function-pointers

我需要解决这个问题.有一个基类和两个继承的类.基类包含需要函数指针作为参数的方法.但是这些函数是在继承的类中定义的.

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);
        ...
    }
};
Run Code Online (Sandbox Code Playgroud)

MSVC 2005编译器在WaitEvent调用上给出错误:

错误C2664:'CBase :: WaitEvent':无法将参数1从'bool(__thiscall CChildA ::*)(void)'转换为'FPredicate'

一个问题是:如何更改代码以使其工作?将WaitEvent调用重写为安全 WaitEvent((FPredicate)(&CChildA::a1), 100)吗?

在这种情况下编译器告诉没有错误,但它是否安全?或者有更好的方法来解决问题吗?

先感谢您.

Yli*_*sar 3

问题是隐式传递的 this 类型不同。要么你强制转换它,但在存在多重继承的情况下这可能会失败。更好、更强大的解决方案是将签名更改为:

template< typename T >
bool WaitEvent( bool ( T::*predicate )(), int timeout ) { ... }
Run Code Online (Sandbox Code Playgroud)