Templates in C++ allow you to write generic code that works with any data type, which promotes reusability and type safety. Templates can be used for both functions and classes, making them powerful tools in generic programming.
A function template is a way to define a generic function that can work with any data type. Instead of writing multiple versions of a function for different data types, you can use a single template function that is instantiated with the correct data type when called.
template <typename T>
T functionName(T arg1, T arg2) {
return arg1 + arg2; // This function works for any type T
}
template <typename T>: This defines a placeholder T that can represent any data type.T functionName(T arg1, T arg2): The function will accept two arguments of type T and return a result of type T.#include <iostream>
using namespace std;
// Function template for addition
template <typename T>
T add(T a, T b) {
return a + b; // Adds two values of type T
}
int main() {
cout << add(5, 3) << endl; // Works with int
cout << add(2.5, 3.7) << endl; // Works with double
cout << add(1.2f, 2.8f) << endl; // Works with float
return 0;
}
add() function is a template that can accept any type T (such as int, double, or float).add(5, 3) is called, it is instantiated with T = int, and similarly for other data types.A class template allows you to define a generic class that can be used with any data type. You can create a single class template that works with multiple data types, eliminating the need to define the same class for different types.
template <typename T>
class ClassName {
T value; // Member of type T
public:
ClassName(T val) : value(val) {} // Constructor
T getValue() {
return value; // Getter function
}
};
template <typename T>: Defines the type placeholder T.T value;: A class member that can hold a value of type T.ClassName(T val): A constructor that initializes the value with a parameter of type T.#include <iostream>
using namespace std;
// Class template to hold a value of type T
template <typename T>
class Box {
private:
T value; // Variable of type T
public:
// Constructor to initialize the value
Box(T val) : value(val) {}
// Function to get the stored value
T getValue() {
return value;
}
};
int main() {
Box<int> intBox(10); // Box of int
Box<double> doubleBox(3.14); // Box of double
Box<string> stringBox("Hello"); // Box of string
cout << "Integer Box: " << intBox.getValue() << endl;
cout << "Double Box: " << doubleBox.getValue() << endl;
cout << "String Box: " << stringBox.getValue() << endl;
return 0;
}
Box is a template class that can hold values of any data type.main(), we instantiate the Box class for int, double, and string.getValue() function returns the value stored inside the Box object.Although templates allow for generic programming, there are situations where you might want to define a specific version of a function or class for a particular type. This is where template specialization comes in. Template specialization allows you to define a specific implementation for a given type while keeping the generic version for other types.
template <>
class ClassName<Type> {
// Special implementation for Type
};
#include <iostream>
using namespace std;
// Generic class template
template <typename T>
class Box {
private:
T value;
public:
Box(T val) : value(val) {}
T getValue() {
return value;
}
};
// Specialization for bool type
template <>
class Box<bool> {
private:
bool value;
public:
Box(bool val) : value(val) {}
bool getValue() {
return value;
}
void display() {
cout << (value ? "True" : "False") << endl;
}
};
int main() {
Box<int> intBox(10);
Box<double> doubleBox(3.14);
Box<bool> boolBox(true); // Specialization for bool
cout << "Integer Box: " << intBox.getValue() << endl;
cout << "Double Box: " << doubleBox.getValue() << endl;
cout << "Bool Box: ";
boolBox.display(); // Specialized method for bool type
return 0;
}
Box<bool> class is specialized to handle the bool type, and it has a display() function to print "True" or "False".Box works for types like int and double.Code Reusability:
Type Safety:
Efficiency:
Flexibility:
Standard Template Library (STL):
vector, list, map, and algorithms like sort, find, and accumulate that work with any type.Generic Data Structures:
Mathematical and Scientific Libraries:
float, double, or int).Function Templates:
Class Templates:
Template Specialization:
Benefits:
By leveraging templates, C++ allows for the creation of generic and flexible code that can be reused across multiple types, making your programs more robust and maintainable.
Open this section to load past papers