Reputation: 1
Okay so I am relatively new to c++ and I am trying to figure out how to use function pointers. I have a function which is a simple numerical integration and I am trying to pass to it which function to integrate and what the limits of integration are. I am doing this in Xcode and the error is in the main code saying "no matching function to call SimpsonIntegration". If someone could please help I would appreciate it. Also since I am learning, any other criticism will be appreciated as well. The main.cpp function is below.
#include <iostream>
#include "simpson7.h"
#include <cmath>
using namespace std;
int main(int argc, const char * argv[])
{
double a=0;
double b=3.141519;
int bin = 1000;
double (*sine)(double);
sine= &sinx;
double n = SimpsonIntegration(sine, 1000, 0, 3.141519);
cout << sine(0)<<" "<<n;
}
The simpson.h file is below:
#ifndef ____1__File__
#define ____1__File__
#include <iostream>
template <typename mytype>
double SimpsonIntegration(double (*functocall)(double) ,int bin, double a, double b);
extern double (*functocall)(double);
double sinx(double x);
#endif /* defined(____1__File__) */
The simpson.cpp file is next:
#include "simpson7.h"
#include <cmath>
#include <cassert>
//The function will only run if the number of bins is a positive integer.
double sinx(double x){
return sin(x);
}
double SimpsonIntegration( double (*functocall)(double), int bin, double a, double b){
assert(bin>0);
//assert(bin>>check);
double integralpart1=(*functocall)(a), integralpart2=(*functocall)(b);
double h=(b-a)/bin;
double j;
double fa=sin(a);
double fb=sin(b);
for (j=1; j<(bin/2-1); j++) {
integralpart1=integralpart1+(*functocall)(a+2*j*h);
}
for (double l=1; l<(bin/2); l++) {
integralpart2=integralpart2+(*functocall)(a+(2*l-1)*h);
}
double totalintegral=(h/3)*(fa+2*integralpart1+4*integralpart2 +fb);
return totalintegral;
}
Well okay now that I fixed that silly error I tried to compile and I got this error: "Linker command failed with exit code 1".
Upvotes: 0
Views: 1156
Reputation: 409404
If you look at the header file, you have this declaration
template <typename mytype>
double SimpsonIntegration(double (*functocall)(double) ,int bin, double a, double b);
And in the source file you have
double SimpsonIntegration( double (*functocall)(double), int bin, double a, double b)
That is not the same function. The compiler tries to search for the non-template function, but that hasn't been declared and so it gives an error.
The simple solution is to remove the template specification in the header file.
If you do want the function to be a template function, then you should be careful with the separation of the declaration and definition, see e.g. this old question.
Upvotes: 4