I've seen a few posts on here about the use of template functions and about questions from the book C++ Accelerated (Koeing/Moo) but none of them answer my questions so I'm hoping you can help.
The question I am struggling with is; "The various analysis functions we wrote is Sect 6.2/110 share the same behaviour; they differ only in terms of the functions they call to calculate the final grade. Write a template function, parameterized by the type of the grading function, and use that function to evaluate the grading schemes. "
I'm still in the early stages of learning, and I would really appreciate some help with this question as I have been stuck on it for weeks and no amount of Googling has helped. Everything I have read refers to referencing, or pointers - which the book has not yet covered so I find it even more confusing.
The 3 analysis functions are all very similar - included below - and I think the question is asking me to write a template function that will replace all 3. I have written a function that I think might work - see below - but I am getting errors when I try to compile because the function write_analysis that uses all of the original analysis functions can not cope with my template function.
I am completely stuck and would really appreciate any help.
I have tried not to include to much code to start with so I hope the below is sufficient.
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
|
double median_analysis(const vector<Student_info>& students)
{
vector<double> grades;
transform(students.begin(), students.end(),back_inserter(grades), grade_aux);
return median(grades);
}
double optimistic_median_analysis(const vector<student_info>& students){
vector<double> grades ;
transform(students.begin(), students.end(), back_inserter(grades), optimistic_median) ;
return median(grades) ;
}
double average_analysis(const vector<Student_info>& students)
{
vector<double> grades;
transform(students.begin(), students.end(),back_inserter(grades), average_grade) ;
return median(grades);
}
|
My attempt at a solution is;
1 2 3 4 5 6 7 8 9
|
template <typename F > double Tanalysis(F Func(const student_info&))
{
std::vector<double> grades ;
transform(students.begin(), students.end(), back_inserter(grades), Func) ;
return median(grades) ;
}
|
The Write_analysis function that is causing my current problem is;
1 2 3 4 5 6 7 8 9
|
void write_analysis(ostream& out, const string& name,
double analysis(const vector<student_info>&),
const vector<student_info>& did,
const vector<student_info>& didnt){
out << name << " : median(did) = " << analysis(did) <<
" : median(didnt) = " << analysis(didnt) << endl ;
}
|
This is my first time posting so I hope the content is sufficient and the format ok. Sorry if it is not, but any help would be appreciated.