Reputation: 399
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);
}
};
Is their any way to overcome this error. I want to pass the filler function and avoid the code smell of duplicate code.
Upvotes: 2
Views: 367
Reputation: 372694
I think the issue here is that you are passing as a parameter the following:
&B::filler
This is a pointer-to-member-function of a function defined in B
. In the base class, you are trying to call it as
(this->*ptrFn)(a);
The problem here is that if the receiver object isn't actually an object of type B
, this would cause a serious runtime error, because you'd be calling a method in B
on an object whose type wasn't B
. C++ is giving you a compiler error to tell you that this is not allowed.
To fix this, change the call to pass in
&A::filler
This is a method in A
, so any A
object will have this particular method. C++ will automatically resolve the call virtually to refer to the most derived implementation of that method, so it should call the B
version of the function in this case.
Hope this helps!
Upvotes: 2