Templates in C++
Templates are a powerful feature in C++ that allow you to write generic code. They provide a way to create functions and classes that can operate on different data types without sacrificing code reusability and type safety. In this lesson, we'll explore the concept of templates in C++ and how they can be used to write flexible and efficient code.
Function Templates
Function templates in C++ allow you to define functions that can be used with different data types. You can create a generic function by using a placeholder type, typically denoted as
T
, and then use that type within the function's definition. When the function is called, the compiler automatically generates the appropriate code for the specific data type.
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
int result1 = add(5, 10);
float result2 = add(3.14, 2.5);
double result3 = add(10.5, 7.2);
// The compiler generates the appropriate code for each data type
}
Class Templates
Class templates in C++ allow you to define generic classes that can work with different data types. Similar to function templates, you can use placeholder types within the class definition and the compiler will generate the appropriate code when the class is instantiated with a specific data type.
template <typename T>
class Stack {
private:
T data[100];
int top;
public:
Stack() : top(-1) {}
void push(T item) {
data[++top] = item;
}
T pop() {
return data[top--];
}
};
int main() {
Stack<int> intStack;
intStack.push(10);
intStack.push(20);
int result1 = intStack.pop();
Stack<double> doubleStack;
doubleStack.push(3.14);
doubleStack.push(2.5);
double result2 = doubleStack.pop();
// The compiler generates separate code for each instantiation of the Stack class
}
Conclusion
Templates in C++ provide a powerful mechanism for writing generic code that can work with different data types. Function templates and class templates allow you to create flexible and reusable code without sacrificing type safety. By leveraging templates, you can write more efficient and concise code that adapts to varying data types. Templates are an essential tool in the C++ programmer's toolkit, enabling code abstraction and code generation based on types. Take advantage of this feature to make your C++ programs more versatile and maintainable.