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. š”
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. ā
Templates are defined using angle brackets < >. For example:
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. š
To use a template, you must instantiate it with specific types. For instance:
int x = 10;
int y = 20;
swap<int>(x, y); // Instantiate the swap template with int typeC++ supports three types of template parameters:
T in our swap example) - used for data types.N in the following array example) - used for numeric values.Let's create a simple array template that works for different data types:
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:
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] = "!";Question: What does the T in the following template declaration represent?
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.