Non-static functions as arguments

DSP, Plugin and Host development discussion.
Post Reply New Topic
RELATED
PRODUCTS

Post

Hey guys,
I'm currently using a Newton-Raphson function that takes a function as a parameter

Code: Select all

typedef double (*func)(double)

inline double NewthonRaphson( func f, double x0)
{
   //do NR stuff
   ...
   return NewtonRaphson(f, x0);
}
The problem is that it only accepts static member functions and, those, won't accept global variables unless they are static too.

Is there a way to make that working without using static functions?

Thanks,
Luca

Post

If you can use C++11 or newer, a solution is to use a function template and lambdas :

Code: Select all

template<typename F>
inline double NewthonRaphson( F f, double x0)
{
   //do NR stuff
   ...
   return NewtonRaphson(f, x0);
}

// To use, inside a class method :
double result = NewtonRaphson([this](double x){ return amemberfunctionofthis(x); },whateverparametergoeshere);


Post

nowadays (since C++11), i would use std::function for this (passed by const reference to your root finder). it can wrap functors (i.e. classes that implement the ()-operator for function evaluation) or lambda-functions (where you can, inside the lamda definition, call any member function of your object) or plain old function pointers. btw. wouldn't you have to pass a second function for evaluating the derivative? or are you planning to use numeric (finite difference) approximations? in this case, you are probably better off with regula falsi or even better brent's method
My website: rs-met.com, My presences on: YouTube, GitHub, Facebook

Post

Music Engineer wrote: Thu Oct 18, 2018 5:04 pm i would use std::function
It is probably slower than the template based solution I gave above. (It would depend on if the compiler can see through the std::function mechanisms and optimize them away.)

Post

Here's a good implementation of what you're looking for. It uses the function template method described by Xenakios. https://github.com/VCVRack/Rack/blob/v0 ... sp/ode.hpp
VCV Rack, the Eurorack simulator

Post

For what it's worth, here is another toy https://github.com/cheind/cppopt
~stratum~

Post

Thanks guys. The lambda solution works like a charm.

Post Reply

Return to “DSP and Plugin Development”