Exercise · Templates · lesson 11 of 11
Exercise: a running sum
Write the class template Tally, a running sum of values of type T; add the fields yourself. The variadic method template <typename... Ts> void add(Ts... xs) adds all its arguments to the sum. T total() const returns the sum, and int count() const returns how many values all calls to add received.
In the examples, points is a Tally<int>, grams a Tally<double>, and text a Tally<std::string>:
- after
points.add(3, 4, 5)andpoints.add(10):points.total()→22,points.count()→4 - after
grams.add(1.5, 2.25):grams.total()→3.75 - after
text.add("ab", "cd")andtext.add("ef"):text.total()→"abcdef"
Constraints: the arguments of add are numbers of type T or, for a Tally<std::string>, text in double quotes. Strings are joined in the order of the calls and the arguments, and calling add() with no arguments changes nothing.