I have a exercise in C++ Primer 6th:
Complete the program by supplying the
average_list()
function. It should be a template function, with the type parameter being used to specify the kind ofinitialized_list
template to be used as the function parameter and also to give the function return type.
I have no idea with it
Here is part of a short program:
int main() {
using namespace std;
// list of double deduced from list contents
auto q = average_list({15.4, 10.7, 9.0});
cout << q << endl;
// list of int deduced from list contents
cout << average_list({20, 30, 19, 17, 45, 38} ) << endl;
// forced list of double
auto ad = average_list<double>({'A', 70, 65.33});
cout << ad << endl;
}
You might go with something like this:
#include <iterator>
#include <numeric>
#include <iostream>
#include <initializer_list>
template <typename T>
auto average_list(const std::initializer_list<T> &&v) -> decltype(T() / 1.0)
{
return std::accumulate(std::begin(v), std::end(v), T()) / static_cast<float>(std::distance(std::begin(v), std::end(v)));
}
The line
auto average_list(const std::initializer_list<T> &&v) -> decltype(T() / 1.0)
Says that average_list
takes an initializer list const reference to some type T
, and returns the type obtained by dividing a T
by a float.
The function's body simply uses STL functions from numeric
and such.