Mastering C++ Class Templates: From Basics to Advanced Usage
This article explains the core concepts of C++ class templates, covering their definition, basic syntax, simple examples, multi-parameter templates, default parameters, specialization, and practical applications such as generic containers and a stack implementation, while offering best practices for effective template programming.
This article delves into another core concept of C++ template programming—class templates. Class templates enable writing generic classes independent of data types, greatly improving code reuse and flexibility.
What is a Class Template?
A class template is a blueprint for creating generic classes or data structures; it uses one or more type parameters. With a class template you can define a set of operations once and reuse them for many different data types without rewriting code.
Basic Syntax
The basic definition syntax is as follows:
template <typename T>
class ClassName {
// class member declarations and definitions
};Alternatively, the class keyword can replace typename:
template <class T>
class ClassName {
// class member declarations and definitions
};Here T is the type parameter that can be used inside the class body as an actual type.
A Simple Class Template Example
Consider a simple Box class template:
#include <iostream>
using namespace std;
template typename T>
class Box {
private:
T content;
public:
Box(const T& newContent) : content(newContent) {}
T getContent() const { return content; }
void setContent(const T& newContent) { content = newContent; }
void display() const { cout << "Box contains: " << content << endl; }
};Using Class Templates
When using a class template you must explicitly specify the template argument when creating an object:
int main() {
// Box storing an int
Box<int> intBox(42);
intBox.display();
// Box storing a double
Box<double> doubleBox(3.14159);
doubleBox.display();
// Box storing a string
Box<string> stringBox("Hello, Templates!");
stringBox.display();
return 0;
}Output:
Box contains: 42
Box contains: 3.14159
Box contains: Hello, Templates!Class Templates with Multiple Parameters
Class templates can accept multiple type parameters:
template typename T, typename U>
class Pair {
private:
T first;
U second;
public:
Pair(const T& f, const U& s) : first(f), second(s) {}
T getFirst() const { return first; }
U getSecond() const { return second; }
void display() const { cout << "Pair: (" << first << ", " << second << ")" << endl; }
};
// Usage examples
Pair<int, string> person(1, "Alice");
Pair<string, double> product("Apple", 2.99);Default Template Parameters
C++ allows default values for template parameters:
template typename T = int, int SIZE = 10>
class Array {
private:
T elements[SIZE];
public:
T& operator[](int index) { return elements[index]; }
// other member functions...
};
Array<> defaultArray; // int, size 10
Array<double> doubleArray; // double, size 10
Array<string, 5> strArray; // string, size 5Specialization and Partial Specialization
Like function templates, class templates support full and partial specialization:
// Primary template
template typename T>
class Calculator {
public:
T add(T a, T b) { return a + b; }
};
// Full specialization for const char*
template<>
class Calculator<const char*> {
public:
const char* add(const char* a, const char* b) {
static char result[256];
strcpy(result, a);
strcat(result, b);
return result;
}
};Practical Application: Implementing a Simple Stack
A generic stack class template can be written as follows:
template typename T>
class Stack {
private:
vector<T> elements;
public:
void push(const T& value) { elements.push_back(value); }
void pop() { if (!empty()) elements.pop_back(); }
T top() const {
if (!empty()) return elements.back();
throw out_of_range("Stack<>::top(): empty stack");
}
bool empty() const { return elements.empty(); }
size_t size() const { return elements.size(); }
};
// Usage examples
Stack<int> intStack;
Stack<string> stringStack;Best Practices
Place the full definition in header files because the compiler needs the complete template definition to instantiate it.
Use member function templates to define additional templated functions inside a class template.
Pay attention to type constraints to ensure the template works meaningfully for all intended types.
Provide clear error messages, for example by using static_assert to produce better compile‑time diagnostics.
Conclusion
Write type‑independent generic code.
Improve code reuse and maintainability.
Perform compile‑time type checking for safety.
Create flexible data structures and algorithms.
Mastering class templates is an essential step toward becoming an advanced C++ programmer.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
