What I want to do is:
class A
{
public:
double sum(double a, double b);
double max(double a, double b);
}
template <typename T>
class B
{
std::vector<T> data;
public:
double sum (double a, double b);
double max (double a, double b);
double average( MyFunction, double a, dobule b)
{
double sum = 0;
int n = data.size();
for ( int i = 0; i < n; i++)
sum = sum + data[i].MyFunction(double a, double b)
return sum / n;
}
}
example:
double average( max, double a, double b)
{
double sum = 0;
int n = data.size();
for ( int i = 0; i < n; i++)
sum = sum + data[i].max(double a, double b)
return sum / n;
}
Why?
- it would save me to write function like: average of sum. average of max. average of min which are all pretty similar functions.
- the way it is coded
B< B< A> >
works
What have I tried?
- function pointer
S1:
typedef double (A::*MyFunctionf)(double, double); typedef double (B<A>::*MyFunctionff)(double, double); typedef double (B<B<A> >::*MyFunctionfff)(double, double);
- it Works. Problems:
- it is not beautiful to declare 3-4 typedef of function pointer
- if I want to write the function inside B that sent a function pointer it will be hard coded and only 1 of the 3 typedef can be hard coded. Meaning: it is not working for every cases
- it Works. Problems:
S2 (based on Template typedefs - What's your work around?):
template <typename rtype, typename t> struct CallTemplate { typedef rtype (t::*ptr)(double, double); }; // the function becomes : template <typename T> template<typename rtype> double B<T>::average(CallTemplate<double, T> MyFunction, double a, double b) { double sum = 0; int n = data.size(); for ( int i = 0; i < n; i++) sum = sum + (data[i].*MyFunction)( a, b) return sum / n; }
example:
// makes an error "Myfunction was not declared" + " // dependent-name'{anonymous}::CallTemplate<double, A>::ptr' // is parsed as a non-type, but instantiation yields a type" CallTemplate<double, A>::ptr MyFunction = &A::max; Average(max, t, v);
I do not know where the problem comes from. I have also tried Boost.Function