Reputation: 1089
Hi suppose I have a code like this
// base class
class A {
public:
int CallMyFct(PtrToFCT what){
return what(10);
}
};
class B : public A {
int myInt;
public:
B():myInt(10){}
int myFct1(int val){
return myInt+val;
}
int myFct2(int val){
return myInt*2+val;
}
void Call(void){
int rez1=CallMyFct(&myFct1);
if (rez1!=20)
cout << "You are wrong" << endl;
int rez2=CallMyFct(&myFct2);
if (rez2!=30)
cout << "You are wrong" << endl;
}
};
Now I need to call these MyFct1, MyFct2, etc. from the base class, but I can not use virtual functions. So it is sorta like inversion of inheritance. I dont know if thats even possible. Do you think mem_fun or any other adapter function would work here.
I actually need to figure out what would be that PtrToFCT and how the would I pass myFct1 in the CallMyFCT.
Thanks
Upvotes: 0
Views: 221
Reputation: 640
You can do what you like more cleanly with [boost::function<>]
1, also known as std::function
from <functional>
in C++2011. You do not state why you cannot use virtual functions. It is not clear that this method offers a performance enhancement over virtual functions, but there are other reasons not to use virtual functions.
In any event, this meets (my interpretation of) your requirements for calling functions from the base class that behave differently depending on the actual derived class without use of virtual functions. Your example of desired use is not completely clear to me. If this mechanism does not meet your needs, please clarify the needs.
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
class A{
protected:
typedef boost::function<int (int)> CallbackFunc;
// A knows it can call *something* with a particular signature
// but what is called can be overridden by the derived class.
CallbackFunc m_callbackFunc;
public:
A()
{
m_callbackFunc = boost::bind(&A::same,this,_1);
}
int same(int val) const { return val; }
int simulateVirtual(int val) const { return m_callbackFunc(val); }
}; //end class A
class B : public A {
int m_offset;
public:
B(int offset) : m_offset(offset) {
m_callbackFunc = boost::bind(&B::offset,this,_1);
}
int offset(int val) const { return m_offset + val; }
}; // end class B
int main() {
A* pA = new A;
A* pB = new B(42);
std::cout << "simulateVirtual(10) called on a 'real' A instance="
<< pA->simulateVirtual(10) << "\n";
std::cout << "simulateVirtual(10) called via A* on a B instance="
<< pB->simulateVirtual(10) << "\n";
delete pB; // in real life I would use shared_ptr<>
delete pA;
return 0;
} // end main
Upvotes: 0
Reputation: 20272
You have to define the functions to be called as static
, and provide additional parameter to pass to them to the object instance (instead of this
that they would be getting if called as regular member functions).
Upvotes: 2