Class template in C++

Level 4205 keystrokes

Defines a class template Box that can hold a value of any type, then creates a Box<int> and a Box<string> and prints 42 Hello.

C++ code

// T is the type of value the box holds
1template<typename T>
2class Box {
// Private member (class members are private by default)
3 T value;
4public:
// Constructor that stores v
5 Box(T v) : value(v) {}
// Return the stored value
6 T get() { return value; }
7};
8
// The template argument int makes T = int
9Box<int> intBox(42);
// T = string; "Hello" is converted to a string
10Box<string> strBox("Hello");
// Print 42 Hello
11cout << intBox.get() << " " << strBox.get() << endl;

Output

42 Hello
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 11
  • (× 7
  • )× 7
  • ;× 6
  • "× 4
  • {× 3
  • }× 3
  • >× 3
  • :× 2
  • .× 2

More C++ examples at level 4

← C++ typing practice