Reputation: 1
I tried to compile this code and I receive no complain. However, when I run it , it give me an exception error for the last line i.e. cout<<"Norm:"<
Could you please guide me how I can solve this problem. Thank you in advance
#include <stdafx.h>
#include <iostream>
#include <string>
#include <boost/function.hpp>
#include <boost/array.hpp>
using namespace std;
template<typename R,typename D>
class GenericFunction
{
private:
boost::function<R (D)> f;
protected:
GenericFunction(){};
public:
GenericFunction(const boost::function<R (D)>& myFunction){f=myFunction;};
R evaluate(const D& value) const{cout<<"Good Job"<<endl;} ;
R operator ()(const D& value);// const{ return f(value); };
};
template <typename R, typename D, int N>
class ScalarValuedFunction:public GenericFunction<R,boost::array<D, N>>
{
public:
ScalarValuedFunction(const boost::function<R (const boost::array<D, N>)> &myF){};
};
template<typename Numeric, std::size_t N>
Numeric Norm(const boost::array<Numeric , N>& Vec)
{
Numeric Result=Vec[0]*Vec[0];
for (std::size_t i=1; i<Vec.size();i++)
{
Result+=Vec[i]*Vec[i];
}
return Result;
}
double test(double t)
{
return t;
}
int main ()
{
const int N=4;
boost::array<double, N> arr={0.2, .3, 1.1, 4};
ScalarValuedFunction<double, double, N> myfun(Norm<double,N>);
cout<<"Norm:"<<myfun(arr)<<endl;
}
Upvotes: 0
Views: 111
Reputation: 126462
You are not forwarding the function argument to the constructor of the base class:
ScalarValuedFunction(const boost::function<R (const boost::array<D, N>)> &myF)
: GenericFunction<R, boost::array<D, N>>(myF) // <=== ADD THIS
{
} //; <== SEMICOLON NOT NEEDED AFTER A FUNCTION DEFINITION!
Without doing this, the GenericFunction
subobject will get initialized to the default constructor (which is accessible to the derived class because it is declared as protected
), and its member variable f
will also be default-initialized.
Then, when trying to invoke it inside operator ()
(whose definition I suppose is the one you have shown in comments), Ka-Boom.
Upvotes: 3