Function templates (part 2)

This lesson contains approximately 21 minutes of video content.

Template argument deduction

Templates and separate compilation

Activity: Merlin's overloaded insertion operator

Graded Playground Autograder

Activity Prompt:

Merlin was showing off his operator overloading wizardry to his roomies. He asked them to “check out these lines of code”:

std::vector<int> vect; vect << 2;
.-------------------.
| [0]       2       |
+-------------------+
|  0x7ffe3ac02ba0   |
'-------------------'
      Size : 1

And just like that, Merlin added the integer value 2 to the std::vector<int>. Shouts of glee could be heard from outside. He wasn’t through yet though, and showed off once more:

// executed after previous statements
vect << 7 << 11;
.-------------------.
| [2]      11       |
+-------------------+
|  0x7ffe3ac02ba8   |
+-------------------+
| [1]       7       |
+-------------------+
|  0x7ffe3ac02ba4   |
+-------------------+
| [0]       2       |
+-------------------+
|  0x7ffe3ac02ba0   |
'-------------------'
      Size : 3

Having added two more values to vect using operator<<, the group’s excitement was heard across all of Aggieland. He then challenged his friends to define and declare an overloaded operator that does that exhibited here.

▶ TASKWrite the declaration and definition for an overloaded operator<< that adds an object of type T to the back of a std::vector<T>.

Make sure that your definition ensures that expressions such as vect << 2 and vect << 7 << 11 are evaluated correctly.

#include "utilities.hpp" #include <vector> int main() { }
#ifndef UTILITIES_HPP #define UTILITIES_HPP #endif
#include "utilities.hpp" // you should not use this file since you're defining a function template: the // function template's definition must be accessible in each translation unit so // that the compiler can derive a definition from the template to instantiate it // for some concrete type T.