I'm working my way through Accelerated C++, and have run across a problem that I cannot figure out. The text of the question is this:
8-1. Note that the various analysis functions we wrote in §6.2/110 share the same behavior; they differ only in terms of the functions they call to calculate the final grade. Write a template function, parametrized by the type of the grading function, and use that function to evaluate the grading schemes.
The relevant code is this:
- Code: Select all
double grade_aux(const Student_info& s)
{
// compute grade
}
double average_grade(const Student_info& s)
{
// compute grade
}
// median of the nonzero elements of `s.homework', or `0' if no such elements exist
double optimistic_median(const Student_info& s)
{
// compute grade
}
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 average_analysis(const vector<Student_info>& students)
{
vector<double> grades;
transform(students.begin(), students.end(),
back_inserter(grades), average_grade);
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);
}
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;
}
I have not figured a way to template the grading function being called. The only resources I can find only talk about how to template a particular type. I have come up with this:
- Code: Select all
double analysis(const vector<Student_info>& students, double func(const Student_info& s))
{
vector<double> grades;
transform(students.begin(), students.end(),
back_inserter(grades), func);
return median(grades);
}
void write_analysis(ostream& out, const string& name,
double func(const Student_info& s),
const vector<Student_info>& did,
const vector<Student_info>& didnt)
{
out << name << ": median(did) = " << analysis(did, func) <<
", median(didnt) = " << analysis(didnt, func) << endl;
}
But that doesn't seem to answer the questions, as it is not a template function. Any help on this would be appreciated.
