C++ Template Parameters šŸŽÆ

beginner
22 min

C++ Template Parameters šŸŽÆ

Welcome to another exciting lesson at CodeYourCraft! Today, we're diving into the fascinating world of C++ Template Parameters. By the end of this lesson, you'll have a solid understanding of how to use templates, their benefits, and practical examples to help you write cleaner, more efficient code. šŸ’”

What are C++ Template Parameters?

In C++, templates are a powerful feature that allows you to write reusable code by defining functions or classes that work with multiple data types. This eliminates the need for redundant code and makes your code more flexible and adaptable. āœ…

Understanding Template Syntax

Templates are defined using angle brackets < >. For example:

cpp
template <typename T> void swap(T& a, T& b) { T temp = a; a = b; b = temp; }

In the above example, T is a placeholder for the type that will be used when instantiating the template. The swap function works for any data type, making it incredibly versatile. šŸ“

Instantiating Templates

To use a template, you must instantiate it with specific types. For instance:

cpp
int x = 10; int y = 20; swap<int>(x, y); // Instantiate the swap template with int type

Template Types

C++ supports three types of template parameters:

  1. Type Parameters (e.g., T in our swap example) - used for data types.
  2. Non-Type Parameters (e.g., N in the following array example) - used for numeric values.
  3. Template Template Parameters (advanced concept, not covered in this lesson) - used for templates themselves.

A Practical Example: Templated Array

Let's create a simple array template that works for different data types:

cpp
template <typename T, size_t N> class Array { T data[N]; public: T& operator[](size_t index) { return data[index]; } };

Now, you can use this template to create an array of integers or strings:

cpp
Array<int, 5> intArray; intArray[0] = 1; intArray[1] = 2; intArray[2] = 3; Array<std::string, 3> stringArray; stringArray[0] = "Hello"; stringArray[1] = "World"; stringArray[2] = "!";

Quiz šŸ“

Question: What does the T in the following template declaration represent?

cpp
template <typename T> void swap(T& a, T& b) { T temp = a; a = b; b = temp; }

A: Type placeholder B: Numeric value placeholder C: Template placeholder Correct: A Explanation: The T in this example is a placeholder for the type that will be used when instantiating the template.