Template Specialization in C++

Level 5525 keystrokes

A full specialization (template<>) gives Serializer a separate implementation for int and for string, while every other type uses the generic primary template. double has no specialization, so it gets "[object]".

C++ code

// Primary template: used for any type without a specialization
1template<typename T>
2class Serializer {
3public:
// Generic fallback result
4 static string serialize(const T& value) {
5 return "[object]";
6 }
7};
8
// template<> starts a full specialization
9template<>
// Version used only when T is int
10class Serializer<int> {
11public:
12 static string serialize(int value) {
// to_string converts the number to text
13 return "int:" + to_string(value);
14 }
15};
16
17template<>
// Version used only when T is string
18class Serializer<string> {
19public:
20 static string serialize(const string& value) {
// Wraps the value in double quotes
21 return "string:\"" + value + "\"";
22 }
23};
24
// Uses the int specialization: prints "int:42"
25cout << Serializer<int>::serialize(42) << endl;
// "hello" is converted to string: prints string:"hello"
26cout << Serializer<string>::serialize("hello") << endl;
// No specialization for double: the primary template prints "[object]"
27cout << Serializer<double>::serialize(3.14) << endl;

Output

int:42
string:"hello"
[object]
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.

  • <× 20
  • "× 12
  • :× 11
  • ;× 9
  • >× 8
  • (× 7
  • )× 7
  • {× 6
  • }× 6
  • +× 3

More C++ examples at level 5

← C++ typing practice