vendredi 12 mai 2023

Higher order functions in C++: Creating an integrator that accepts member functions

I would like to create a function-object class that numerically integrates some functions on-demand. Its public interface would consist of a method void T::step(double dt) that computes an integration step (and updates the internal state of the function-object with the new values), and getters to the current calculated values.

While I'm sure this could be done with pure stand-alone functions, the functions I'll be integrating have many intermediate calculation steps in common, and depend on many internal parameters which must be updated on every step (and are largely irrelevant to the user), so I thought of using a function-object to encapsulate this mechanism.

But now I've found myself wrestling the type-system, trying to define a function double integrate(double t, double dt, METHOD f) to actually compute each individual function's integration step, accepting member functions as arguments.

I've come up with

template <typename T>
double integrate(double t, double dt, double (T::*f)(double), T* obj)
{
  // Here I can reference `obj->*f(...)`
}

but I'm a bit uneasy, as it seems contrived and some people make it seem like function pointers are the devil when it comes to performance.

Using only C++11 features, is there a cleaner, more performant or more idiomatic approach to this?

Aucun commentaire:

Enregistrer un commentaire