I have written an integration function (of one variable)

double integrate(double (*f)(double), const double a,  const double b)

However, now I want to integrate a function of one variable, but the c++ function has an additional parameter:

double f(double x, bool flag)
{
if(flag == true)
  f = pow(x,2);
else
  f = pow(x,3);
}

I can't pass that to my integrate() function because it has the wrong number of arguments. How do you get around this?

Thanks,

Dave

I've never done anything like that myself, but perhaps add a bool parameter to you function pointer that is default (= to) false? If you don't add the functionality to integrate, then you might as well rewrite the power function to only return a square of the number, since it will never be able to pass its flag to integrate.

That's a good idea for that simple case, but that was just an abstraction of my case.

I really have something more like this:

double f(double x, double clutter, double mismatch)
{
  f = pow(x,2) + clutter + 2*mismatch;
}

Where I want to integrate over the first variable, and the rest of the arguments are just constants.

Dave

Hmmm well you COULD just use an elipsis (...) to indicate that there are a variable number of arguments. You might want to google this, but I'm pretty sure it's passed in the form of an array in that case. But I've never done this before either because, personally, the elipses scares me.

Here's what I did:

class FunctionClass
{
	public:
		virtual double f(const double x) = 0;
};

double integrate(FunctionClass &Func, const double a, const double b, const double epsilon = 1e-6);

Inside Integrate() I can use Func.f(some double).

Then In main.cpp I do

class MyFunction : public FunctionClass
{
	public:
		double a;
		
		double f(const double x)
		{
			return pow(x,2) + a;
		}
};

int main()
{
	MyFunction TestFunction;
	TestFunction.a = 10;
	
	cout << integrate(TestFunction, 0, 5) << endl;

I guess this is the "new" style of passing function pointers? haha

Dave

It is impossible to do without classes or global variabes?

The class method above use tha same trick
as you use a global variable.
If "a" is a global variable instad of class variable inside the class,
works fine also. But not so general or beautifull.

easy way :

you can wrap another bool parameter.

double integrate( pointer_func Pf, int low, int high, bool flag, bool doFlag)
{
    if( doFlag == true) { if( flag == true) { /* something */ } }
  else //blah blah
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.