Template Specialization

Partial and full specialization

Interview Relevant: Advanced templates

Template Specialization

Provide specific implementations for certain types.

Code Examples

Template specialization for type-specific behavior.

cpp
1// Primary template
2template<typename T>
3class Printer {
4public:
5    void print(const T& value) {
6        cout << value << endl;
7    }
8};
9
10// Full specialization for bool
11template<>
12class Printer<bool> {
13public:
14    void print(const bool& value) {
15        cout << (value ? "true" : "false") << endl;
16    }
17};
18
19// Partial specialization for pointers
20template<typename T>
21class Printer<T*> {
22public:
23    void print(T* value) {
24        cout << "Pointer: " << *value << endl;
25    }
26};
27
28Printer<int> p1;
29p1.print(42);       // 42
30
31Printer<bool> p2;
32p2.print(true);     // true
33
34int x = 5;
35Printer<int*> p3;
36p3.print(&x);       // Pointer: 5

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In