I am not an advanced programmer. Short version of the problem: how can I create a template for a global function that calls a pointer to a member function of a class that is known only at runtime (and who has different arguments)?
The function is global, and its declaration is as follows:
template<class T> const double gExtFunc(const double &x, \ const double &y, \ const double &ep, \ const double &es, \
This is called inside some ( virtual public ) classes. For example (not using ellipsis ):
class DerivedA: virtual public Base { public: void funcA(...) {
The Base class is for ordinary variables only. A pointer to a function points to commonFunc() , which has the same name in all virtual classes, but different definitions and types of arguments in each. For example, the above DerivedA uses it with two const double& arguments, whereas a DerivedE with:
const double DerivedE::commonFunc(const int &n, const double &k) const;
Now I managed to get it to work with the lambda function (based on this when I had only one m_varA ), which meant the argument of the function pointer from gExtFunc() :
const double gExtFunc(..., std::function<const double(const double&, const double&)> fPnt, ...)
and he was called, for example. inside DerivedA , as:
m_varA = gExtFunc(..., [this](const double &a, const double &k){ return commonFunc(a, k); }, ...)
and he worked, but only as long as he was called only within one class. As soon as I tried to call it DerivedE , it also failed for m_varE : was not declared in this scope , pointing to its definition of m_varE .
I saw this answer, but for this I need to first create an object that I cannot do. So I tried to get around this and replace the pointer to the function argument as follows:
template<class T> // first the template, above the function const double gExtFunc(..., T *t, const double(T::*t)(const double&, const double&) fPnt, ...)
and inside the definition: t->fPnt(...) . But what could you call gExtFunc() ? I tried this:
m_varA = gExtFunc(..., new DerivedA(), &DerivedA::commonFunc, ...)
but it fails, was not declared in this scope , as above. I'm stuck here. If there is an alternative to what I'm trying to do, I really want to change it.
EDIT:
As a temporary, ugly solution, I copied gExtFunc() each class that needs it, truncated and adjusted, including refusing a function pointer, only a direct call to the member function commonFunc() . At the moment there are only 3 cases, but the future can bring more, so I find it ugly and why the issue is still valid.