Templates are a powerful feature in C++ that allow you to write generic code. They enable you to create functions and classes that can work with different data types without having to write separate versions for each type. This promotes code reusability and reduces code duplication.
A function template defines a generic function that can be used with various types. The compiler generates the specific function code for each type when it's needed.
template <typename T>
T myFunction(T a, T b) {
return a + b;
}
int main() {
int sumInt = myFunction(5, 10); // T is int
double sumDouble = myFunction(3.14, 2.71); // T is double
// char concatenated = myFunction('A', 'B'); // T is char
return 0;
}
In this example, myFunction
is a function template. The typename T
specifies that T
is a type parameter. The compiler deduces the type of T
based on the arguments passed to the function.
Class templates allow you to create generic classes that can work with different data types. This is particularly useful for container classes like vectors, lists, and maps.
template <typename T>
class MyVector {
private:
T* data;
int size;
public:
MyVector(int s) : size(s) { data = new T[size]; }
~MyVector() { delete[] data; }
T& operator[](int i) { return data[i]; }
};
int main() {
MyVector<int> intVector(10); // T is int
MyVector<double> doubleVector(5); // T is double
intVector[0] = 10;
doubleVector[0] = 3.14;
return 0;
}
Here, MyVector
is a class template. You must specify the type when you create an instance of the class (e.g., MyVector<int>
).
Templates can also have non-type parameters, like integers. This can be useful for things like specifying the size of an array at compile time.
template <typename T, int N>
class MyArray {
private:
T data[N];
public:
// ... methods to work with the array
};
int main() {
MyArray<int, 10> intArray; // Creates an array of 10 ints
MyArray<double, 5> doubleArray; // Creates an array of 5 doubles
return 0;
}
Templates are a powerful tool for generic programming in C++. They allow you to write flexible and efficient code that can work with a variety of data types.