I'm having trouble getting member function pointers to work (I don't know whether what I'm trying to do is possible). I want to set a member variable (which is a pointer to a non-static function in another class) and then call that function. I then want to be able to set it to another member function in a different derived class and call that. The 2 derived classes are created by templates, as per below. Can I achieve this and if so, what am I doing wrong?
// Forward declare these, their implementation is irrelevant to the question
class A;
class B;
// declare a base class that contains a function log() that we want to call
class BaseClass {
public:
BaseClass() {}
virtual ~BaseClass() {}
virtual void log() {} // want to call this via function pointers
};
//Using a template means we don't have to specify the type in the vector
template<class T>
class TemplateVectorOfBaseClass : public BaseClass {
protected:
std::vector<T> peripherals;
}
// this specific implementation does stuff using Class A
template <int randomTemplateParameter>
class DerivedTemplateClassThatDoesStuffWithAs : public BaseClass
public:
DerivedTemplateClassThatDoesStuffWithAs() : TemplateVectorOfBaseClass<A>() {}
void log() {do_something_here_involving_As();}
int i[randomTemplateParameter];
};
// this specific implementation does stuff using Class B
template <int randomTemplateParameter>
class DerivedTemplateClassThatDoesStuffWithBs : public BaseClass
public:
DerivedTemplateClassThatDoesStuffWithBs() : TemplateVectorOfBaseClass<B>() {}
void log() {do_something_here_involving_Bs();}
float f[randomTemplateParameter];
};
// Class that contains both templates as member variables
class ContainerClass {
public:
ContainerClass();
DerivedTemplateClassThatDoesStuffWithAs dtca<5>;
DerivedTemplateClassThatDoesStuffWithBs dtcb<10>;
void (BaseClass::*log)(); // pointer to member function log()
}
// usage
ContainerClass cc;
cc.container.log = &dtca.log;
cc.*log(); // should call vectorContainingAs.log()
cc.container.log = &dtcb.log;
cc.*log(); // should call vectorContainingBs.log()
class ContainerClass { public: ContainerClass container;. How could this ever compile?