I have a caller function like this:
template
void CallMethod(T *object){
(object->*method)(args);
}
It looks like you're trying to implement an interface via templates. It might be possible, but wouldn't it be nicer to have a base class with a virtual function, and use a base class pointer to access the virtual function via a simple function call?
Header:
class AbstractBase
{
public:
virtual void func() = 0;
}
class SubClass : public AbstractBase
{
public:
void func();
}
Source file:
void SubClass::func()
{
std::cout << "Virtual function called.\n";
}
Example usage:
int main()
{
AbstractBase* base;
base = new SubClass();
base->func(); // virtual function call through base pointer will use SubClass's implementation
return 0;
}
You can store a vector of pointers (or smart pointers if you use boost or C++0x) which you can loop through and use this to do all kinds of SubClass dependent stuff.
Alternatively, use boost::function
or std::function
(C++0x) which is an object containing the member function in question and pass that as a template parameter, using the object instance as a first argument. Which comes down to a workaround of the above.
UPDATE: Seeing that you need a plain C function pointer, there are some tricks that might imapct runtime performance in c++0x or boost: bind
, function::target
and so forth...
You will need this to get a function pointer out of a std/boost::function, and this to bind the first argument to an object. bind
acts at runtime, so maybe a template would be better in this case...