1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
#include <iostream>
#include <cmath>
template<typename T>
class FunctionBase { // Base class. Here I define a simple interface
public: // which evaluates the value of a function
virtual T operator() (T x) = 0;
virtual ~FunctionBase(){ } // Virtual destructor
virtual int getError() = 0; // This should return error flag.
};
template<typename T, class parameters, typename S>
class Function : public FunctionBase<T> { // Here I define derived class
public:
typedef T definition( T, parameters&, S& );
definition& function; // math functions are evaluated at point T x
parameters& params; // with parameters.
S& error_flag; // If value of the math function is not valid
// then this value should change. But unfortunately it
// doesn't. Overload () operator in function evaluations.
virtual T operator() (T x){
return function( x, params, error_flag );
}
virtual ~Function(){ }
int getError(){
return error_flag;
}
// Constructors
Function( definition& function_ ) : function( function_ ), params( 0 ),
error_flag( 0 ) { }
Function( definition& function_, parameters& params_, S error_flag_ )
: function( function_ ), params( params_ ),
error_flag( error_flag_ ) { }
};
// Example function
double fun( double x, double& alpha, int& error ){
double result = alpha*x;
if ( !isinf( result ) ){
error = 0;
return result;
} else {
error = 1;
return 0.0;
}
}
int main(){
int status = 1;
double x = 2.0;
double a = 1;
Function<double, double, int> F(fun, a, status);
std::cout <<"val:" << F(x) << " status: " << F.getError() << std::endl;
return 0;
}
|