CodeWithAbdessamad

Class Templates

Class Templates

Generic programming is the foundation of C++’s power and flexibility. It lets you write code that works with any data type—without sacrificing performance or maintainability. Think of it as creating reusable building blocks that adapt to your specific needs. This section dives deep into class templates, the core mechanism for implementing generic classes in C++. đź§ 

What Are Generic Classes?

Generic classes are classes defined with template parameters that allow them to operate with multiple data types at compile time. Unlike traditional classes tied to a single type (e.g., int or std::string), generic classes work universally. This avoids code duplication and enables safe, type-safe operations across diverse scenarios.

For example, std::vector is a classic generic class—it handles int, double, std::string, and more without modification. This approach eliminates runtime type checks and reduces errors while maximizing code reusability.

Defining a Class Template

Class templates follow this syntax:

<code class="language-cpp">template <template-parameter-list>
<p>class class-name {</p>
<p>    // class body</p>
<p>};</code>

The template keyword declares the template, followed by a list of parameters in angle brackets. Here’s a simple example of a generic Box class that holds any type:

<code class="language-cpp">template <typename T>
<p>class Box {</p>
<p>public:</p>
<p>    T value;</p>
<p>    Box(T t) : value(t) {}</p>
<p>    T get() const { return value; }</p>
<p>};</code>

This template works for any type T (e.g., int, double, std::string). When you instantiate it with Box, the compiler replaces T with int and generates type-safe code.

Key Insight: typename vs. class

  • Use typename for type parameters (e.g., T in Box).
  • Use class for template template parameters (e.g., Template).

Template Parameters Deep Dive

Class templates support three types of parameters:

  1. Type Parameters (typename or class):

Specifies the data type for the template.

Example: template

  1. Non-Type Parameters:

Values (e.g., integers) that influence template behavior.

Example: template

  1. Template Template Parameters:

Templates themselves as parameters.

Example: template