Click to See Complete Forum and Search --> : Function pointers and the like


danielsbrewer
April 15th, 2003, 05:43 AM
Hi there. I was wondering if you could help me to solve my problem or avoid it all together.

I have a class that requires a pointer to a function in its constructor:

Simplexer::Simplexer( double min_func(vector<double>&),
const double tolerance)

And the class performs various algorithms. And this works fine if I pass a function pointer not in a class. The problem occurs when I want to pass it a class function, something like this:

Model model_1(rk,equation);
Simplexer yoyo(model_1.least_squares,1e-8);
cout << yoyo.go() << endl;

And this doesn't work at all. My latest attempt is to do this:
Simplexer yoyo(&(model_1.least_squares),1e-8);

But the error I get is:
src/p53.cc:61: no matching function for call to `Simplexer::Simplexer( double (Model::*)(std::valarray<double>),
double)'

(From gcc).

Any ideas? I know function pointers are a bit dodgy anyhow, so is there a way to get round it?

Thanks

astanley
April 15th, 2003, 06:28 AM
Is model_1 a class or an object (instance of the class)?

Try declaring your class member function (model_1.least_squares) static. It will not be able to use any non-static members of the class, but how could it, as you're not passing the object into the Simplexer constructor.

A redesign may be more appropriate: e.g., a virtual "min_func" function in your Simplexer class, and derive other classes from Simplexer in which you implement different versions of min_func. That is the more o-o way to do this kind of thing.

danielsbrewer
April 15th, 2003, 06:35 AM
Sorry for the confusion. model_1 is an object of class Model.

Thanks

Graham
April 15th, 2003, 07:48 AM
Try this:

template <class T>
class Simplexer
{
public:
Simplexer::Simplexer(double (T::*func)(vector<double>), double tolerance)
: func_(func), tolerance_(tolerance)
{
}

double go(T& object)
{
return (object.*func_)(/*...*/);
}
private:
double (T::*func_)(vector<double);
double tolerance_;
};

int main
{
Model model_1(/*...*/);
Simplexer yoyo(Model::least_squares, 1e-8);
cout << yoyo.go(model_1) << endl;
}

I haven't checked this code, so there may be some errors in it.

The basic point is that member functions are not the same as ordinary functions - they have a different pointer syntax involving the class name.

In my example, I generalised the constructor (and the Simplexer class), but if you're always going to use class Model with it, you can use that explicitly.

danielsbrewer
April 15th, 2003, 09:45 AM
Hmmmmm, I tried that and it still does not work right. Now I get:

rc/p53.cc:61: no matching function for call to `Simplexer::Simplexer(
<unknown type>, double)'

And if I put:
Simplexer yoyo(&(Model::least_squares),1e-8);

I get an internal compiler error! Maybe I should try inheritence

Thanks anyhow.