Multiple type parameters
- C++ course
- Intermediate
- Lesson 50/116
- 5 min
Learn multiple types with template<typename T, typename U>.
Multiple type parameters
A template can take multiple type parameters. template <typename T, typename U> struct Pair { T first; U second; }; declares two type parameters, separated by commas.
Example: Pair<int, double> p; makes first int and second double. p.first = 3; p.second = 3.14; sets the members. The type order matches the declaration: the first type maps to T, the second to U. STL's std::pair and std::map use this pattern.
Using Pair
Instantiate Pair: Pair<int, double> p;. Members are accessed directly: p.first = 3; p.second = 3.14;. The type order must match the declaration.
Wrong order: Pair<double, int> p; p.first = 3.14; p.second = 3; — here first is double and second is int. The types swap. You read which type maps to which member from the declaration. std::pair is often used as a key-value pair in STL algorithms.
Practice Write the Pair template
Write template <typename T, typename U> struct Pair. Inside, have T first; and U second;. In main write Pair<int, double> p;, p.first = 3;, std::cout << p.first << std::endl;.
Starter code
#include <iostream>
// write the Pair template: T first, U second
int main() {
// create a Pair instance and print first
return 0;
}Sample solution
#include <iostream>
template <typename T, typename U>
struct Pair {
T first;
U second;
};
int main() {
Pair<int, double> p;
p.first = 3;
p.second = 3.14;
std::cout << p.first << std::endl;
return 0;
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many type parameters does Pair<int, double> take?
template <typename T, typename U> struct Pair;- Zero
- One
- Three
- Two Correct answer
Explanation: Pair<int, double> takes two type parameters: T and U.
2 Complete the Pair declaration
Pair<int, ____> p;
Pair<int, double> p;
Explanation: Pair<int, double> p; makes the second member double.
3 Match each piece to its role
| Term | Meaning |
|---|---|
typename T, typename U |
Two type parameters |
T first |
First type member |
U second |
Second type member |
Pair<int, double> |
Instantiation |