OOP model
- C++ course
- Intermediate
- Lesson 113/116
- 6 min
Set up the class hierarchy and templates.
Template function: printItem
In this lesson we add a template function named printItem. This function can print any type with std::cout.
Example: template <typename T> void printItem(const T& item) { std::cout << item; }. This function can be called for a std::string, a bool or a Task object. Templates let the same code work for different types. The const T& parameter prevents copying and is efficient for large objects. We take the Task class from the previous lesson and add this template on top.
Calling the template
When calling a template function you do not specify the type explicitly; the compiler deduces it from the parameter. The call printItem(t.title) sets T to std::string.
Example: printItem(t.title); prints the title, printItem(t.done); prints the done flag. The compiler generates the correct type for each call. This is not shorter than writing std::cout << but provides consistency when used repeatedly in a project. Templates are also common in the STL; std::vector is a template too.
Practice Add the printItem template and call it
After the Task class in the starting code, add the printItem template function: template <typename T> void printItem(const T& item) { std::cout << item; }. In main print the title with printItem(t.title), then a space and t.done.
Starter code
#include <iostream>
#include <string>
class Task {
public:
std::string title;
bool done;
Task(std::string t) : title(t), done(false) {}
};
// Add the printItem template function
int main() {
Task t("Homework");
// Print the title with printItem, then a space and done
return 0;
}Sample solution
#include <iostream>
#include <string>
class Task {
public:
std::string title;
bool done;
Task(std::string t) : title(t), done(false) {}
};
template <typename T>
void printItem(const T& item) {
std::cout << item;
}
int main() {
Task t("Homework");
printItem(t.title);
std::cout << " " << t.done;
return 0;
}Expected output
Homework 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the template definition
template <____> void printItem(const T& item) { std::cout << item; }
template <typename T> void printItem(const T& item) { std::cout << item; }
Explanation: typename T is the template type parameter.
2 What does template <typename T> enable?
template <typename T>
void printItem(const T& item);- The function is deleted
- The function is faster
- The function is hidden
- The function works with different types Correct answer
Explanation: A template lets the function work with different types.
3 Match each piece to its role
| Term | Meaning |
|---|---|
template <typename T> |
Template definition |
const T& |
Copy-free parameter |
printItem(t.title) |
Call |
std::cout << item |
Printing |