模板类、继承和指向成员函数的指针的编译器错误

Compiler error with template classes, inheritance, and pointers-to-member-functions

本文关键字:函数 成员 指针 错误 编译器 继承      更新时间:2023-10-16
class A{
    virtual int foo1(int a){ 
        return foo1_1(a,filler(a));
    }   
    template<typename FunctionPtr_filler> 
    int foo1_1(int a, FunctionPtr_filler ptrFn)
    {   
        int b;
        b = (this->*ptrFn)(a);  // --> compile error: pointer to member type int (B::)(int) incompatible with object type A
        return b;
    }   
    protected:
    virtual int filler(int a){ 
        return a*a;
    }   
};
class B: public A{
    virtual int foo1(int a){ 
        return foo1_1(a, &B::filler);
    }   
    virtual int filler(int a){ 
        return (a+a);
    }   
};

他们有什么办法克服这个错误。我想传递填充函数并避免重复代码的代码气味。

我认为这里的问题是您将以下内容作为参数传递:

&B::filler

这是 B 中定义的函数的指向成员函数的指针函数。 在基类中,您尝试将其调用为

(this->*ptrFn)(a);

这里的问题是,如果接收器对象实际上不是类型 B 的对象,这将导致严重的运行时错误,因为您将在类型未B的对象上调用 B 中的方法。 C++给您一个编译器错误,告诉您这是不允许的。

若要解决此问题,请将调用更改为传入

&A::filler

这是A中的一个方法,所以任何A对象都会有这个特定的方法。 C++将自动解析虚拟调用以引用该方法的最派生实现,因此在这种情况下,它应调用函数的B版本。

希望这有帮助!