Summary - Template basics
- C++ course
- Intermediate
- Lesson 52/116
- 5 min
Combine template functions and classes to write a Stack<T>.
Summary - Templates
In this group you learned the basics of templates. A template writes type-independent code. A template function deduces the type at the call. A template class takes a type parameter. Multiple type parameters are comma-separated. Specialization provides a custom version for a specific type.
In the final task you will combine them: write an identity template and a Box template class, then construct a Box<int> instance with identity(42). This shows how templates compose.
Practice Mini task: combine Box and identity
Write template <typename T> T identity(T x) that returns x. Write template <typename T> class Box with private T value, constructor Box(T v) : value(v) {}, T getValue() returning the value. In main write Box<int> b(identity(42)); and std::cout << b.getValue() << std::endl;.
Starter code
#include <iostream>
// write the identity template
// write the Box template class
int main() {
// create a Box<int> instance with identity(42), print getValue()
return 0;
}Sample solution
#include <iostream>
template <typename T>
T identity(T x) { return x; }
template <typename T>
class Box {
T value;
public:
Box(T v) : value(v) {}
T getValue() { return value; }
};
int main() {
Box<int> b(identity(42));
std::cout << b.getValue() << std::endl;
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does template <typename T> declare?
template <typename T>- A variable
- A type parameter Correct answer
- A class
- A function
Explanation: template <typename T> declares a type parameter.
2 Template class instantiation
Box<____> b;
Box<int> b;
Explanation: Box<int> b; is an instance of the template class with int.
3 Match the concepts
| Term | Meaning |
|---|---|
template <typename T> |
General template |
template <> |
Full specialization |
Box<int> |
Class instantiation |
identity(42) |
Function call |