3.6 Generic Programming and Exception Handling
This section explores generic programming in C++, which allows writing flexible, reusable code using templates. We also discuss exception handling, which is used to handle errors gracefully using try, catch, and throw mechanisms.
1. Function Templates
A function template allows you to define a function that works with any data type. It acts as a blueprint for creating functions that can operate on different data types.
Syntax:
template <typename T> T add(T a, T b) { return a + b; }
Example: Using function templates.
#include <iostream>
using namespace std;
template <typename T> // Function template for any type T
T add(T a, T b) {
return a + b;
}
int main() {
cout << add(5, 10) << endl; // Output: 15 (int)
cout << add(3.5, 2.5) << endl; // Output: 6.0 (double)
cout << add('A', 'B') << endl; // Output: 131 (char)
return 0;
}Output:
2. Class Templates
A class template enables you to define a class that can operate with any data type.
Syntax:
Example: Using class templates.
Output:
3. Standard Template Library (STL)
C++ provides the Standard Template Library (STL), which is a collection of template classes and functions. It provides useful data structures and algorithms, making it easier to work with collections of data.
Containers
Containers are used to store collections of data. Some common types are:
Vector: Dynamic array.
List: Doubly linked list.
Queue: FIFO structure.
Stack: LIFO structure.
Map: Key-value pair collection.
Example: Using a vector (dynamic array) container.
Output:
Algorithms
The STL provides useful algorithms for operations like sorting, searching, and manipulating data structures.
Example: Using the sort algorithm to sort a vector.
Output:
Iterators
Iterators are used to traverse through the elements of a container.
Example: Using iterators to traverse a vector.
Output:
4. Exception Handling
Exception handling in C++ helps to manage errors during program execution using the try, catch, and throw mechanisms.
try: A block of code that might throw an exception.
catch: A block of code that handles the exception.
throw: Used to throw an exception.
Syntax:
Example: Basic Exception Handling
Output:
Example: Multiple Exceptions
You can have multiple catch blocks to handle different exceptions.
Output:
Conclusion
Function Templates: Allow you to create generic functions that can work with any data type.
Class Templates: Allow you to define classes that work with different data types, providing flexibility and reusability.
STL:
Containers: Store collections of data (e.g.,
vector,list,map).Algorithms: Predefined functions like
sort(),find(),reverse()to operate on data in containers.Iterators: Used to traverse containers in a generic way.
Exception Handling: Handles errors using
try,catch, andthrow. It ensures that your program can recover gracefully from runtime errors, including handling multiple types of exceptions.
Last updated