Question

I have a class which interpolates a 2D function automatically (quite happy with it). It accepts a dynamic function pointer to the method being interpolated. I have had to template out the class, since I need the object instance as well as the pointer.

Can I avoid templating the class out? Or will I need to keep doing so in order to accept the object instance as a parameter? Is a base class possible? (I'm fairly new to c++)

The way I have it is (abbreviated):

template<class F>
class Interpolate {
   Interpolate(double (F::*f)(double, double), F & obj, ...) { 
      ...
      double value = (object.*f)(x,y);
      ...
   }
}
Was it helpful?

Solution

As pointed out in the comment, you can also use std::function. This give you more flexibility with std::bind. On the other hand, std::function may allocate the resulting function on the heap and this causes a big overhead (which may be avoid by using std::cref() ). A very interesting discussion about the differences in execution time of std::function vs templates can be found at std::function vs template.

" Notice that std::function is able to store different types of callable objects. Hence, it must perform some type-erasure magic for the storage. Generally, this implies a dynamic memory allocation (by default through a call to new). It's well known that this is a quite costly operation. " by Cassio Neri - Here is where std::cref can help, specially because in the example discussed in the link I just wrote, without std::cref, the heap allocation of std::function slowed down the program by a factor 10!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top