Classes and OOP · Lesson 17 of 21
Templates
Write a function or class once and use it with any type.
Instead of writing largest for int, double and string, write it once as a template. The compiler generates a version for each type you use, at compile time, so it's as fast as hand-written code. That's exactly how std::vector<T> and std::map<K, V> are built.
#include <iostream>
#include <string>
#include <vector>
template <typename T>
T largest(const std::vector<T>& items) {
T best = items.at(0);
for (const T& x : items) {
if (x > best) best = x;
}
return best;
}
int main() {
std::cout << largest(std::vector<int>{3, 9, 4}) << "\n";
std::cout << largest(std::vector<double>{2.5, 1.5}) << "\n";
std::cout << largest(std::vector<std::string>{"pear", "apple", "zebra"}) << "\n";
return 0;
}template <typename T> T largest(...)
largest(vector<int>) → compiler generates an int version
largest(vector<string>) → a string version
A template isn't running code; it's a recipe the compiler cooks from.
Class templates
#include <iostream>
#include <string>
template <typename K, typename V>
struct Pair {
K key;
V value;
void print() const { std::cout << key << " => " << value << "\n"; }
};
template <typename T, int N>
struct FixedStack {
T items[N];
int count = 0;
bool push(const T& x) {
if (count == N) return false;
items[count++] = x;
return true;
}
};
int main() {
Pair<std::string, int> p{"xp", 320};
p.print();
FixedStack<char, 2> s;
std::cout << s.push('a') << s.push('b') << s.push('c') << "\n";
return 0;
}Complete the code
Complete the template that swaps two values of any type.
#include <iostream> <typename T> void swapAny(T& a, T& b) { temp = a; a = b; b = temp; } int main() { int x = 1, y = 2; swapAny(x, y); std::cout << x << y << "\n"; }
Exercise
Write a template T sumAll(const std::vector<T>& v) returning the sum, and use it with {1, 2, 3} and {0.5, 0.25}. Two lines of output: 6 and 0.75.
6 0.75
#include <iostream>
#include <vector>
int main() {
std::cout << sumAll(std::vector<int>{1, 2, 3}) << "\n";
std::cout << sumAll(std::vector<double>{0.5, 0.25}) << "\n";
return 0;
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.