Codiqo

Learn C++ · lesson 59 of 61 · about 9 minutes

Class Templates

Write a class once and use it to hold any type, just like std::vector does.

What you'll learn

  • Write a class template
  • Create objects of it with <int>, <std::string> and more
  • Write member functions that use T

The twin chests

At the castle's back gate stand two chests with the same lock. The lids say three, one, four, and the hero has three guesses at the code. One chest holds 25 gold and the other holds a map: Click! The gold chest holds 25 gold. Gold: 95, then The map chest shows the secret stair. A wrong guess gets The lock holds, and after three of them, The chests stay locked. The two chests hold different types of thing, but they lock the same way, so one class template can make both.

Your own std::vector-style class

std::vector<int> and std::vector<std::string> come from one class template. You can write your own: template <typename T> before a class makes T usable everywhere inside it, for members, parameters and return types.

When you create one, you say what T is: Box<int>, Box<std::string>.

A box for anything

#include <iostream>
#include <string>

template <typename T>
class Box {
public:
    explicit Box(T value) : value_(value) {}
    T get() const { return value_; }
    void set(T value) { value_ = value; }

private:
    T value_;
};

int main() {
    Box<int> number(42);
    Box<std::string> word("phoebe");
    number.set(number.get() + 1);
    std::cout << number.get() << " " << word.get() << "\n";
}

Output

43 phoebe

Pairs of anything

A template can have more than one type: template <typename K, typename V>. Then each object chooses both, like Labelled<std::string, int>. This is how std::map<K, V> works.

Two type parameters

#include <iostream>
#include <string>

template <typename K, typename V>
class Labelled {
public:
    Labelled(K label, V value) : label_(label), value_(value) {}
    void show() const { std::cout << label_ << ": " << value_ << "\n"; }

private:
    K label_;
    V value_;
};

int main() {
    Labelled<std::string, int> a("score", 340);
    Labelled<char, double> b('x', 1.5);
    a.show();
    b.show();
}

Output

score: 340
x: 1.5

One chest for anything

Locked<T> keeps its item in a T item_, takes it in the constructor as a T and gives it back from take() as a T. The code is always a whole number, so code_ is just an int, the same in every chest. Locked<int> goldChest(25, 314) holds gold that can be added to the hero's, and Locked<std::string> mapChest("the secret stair", 314) holds words that can be printed.

Tip

Class templates usually live entirely in a header file, because the compiler needs to see the whole template wherever it's used.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.