← C++ from Scratch Lesson 44 of 62 · 10 XP

Templates

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A template is a function or a class "for any type". The compiler creates the version it needs by itself when it's used:

template <typename T>
T maxOf(T a, T b)
{
    return a > b ? a : b;
}

maxOf(3, 7);                     // T = int
maxOf(2.5, 1.5);                 // T = double
maxOf<std::string>("a", "b");    // T is given explicitly

template <typename T>
class Box {
public:
    explicit Box(T v) : value(v) {}
    T get() const { return value; }
private:
    T value;
};
Box<int> b(5);

The whole STL is built on templates: std::vector<int>, std::map<std::string, int> are template classes. The compiler reports errors in templates with long messages — read the first line of the message.

Task. A template function T sumAll(const std::vector<T>&) and a template class Pair<A, B> with the fields first, second and a method swapped() that returns a Pair<B, A>. Read n integers and print their sum; then read n fractional numbers and print their sum with one decimal place; then read a word and a number and print the pair in reverse order: number word.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.