Templates
Templates provide a way to write generic code that works with different data types. They allow you to define functions or classes with placeholders for types, and the compiler generates specific code for each type when the template is used.
Template Function
#include <iostream>
// Template function to find the maximum of two values
template <typename T>
T findMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
// Using the template function with different types
int maxInt = findMax(3, 7);
double maxDouble = findMax(4.5, 2.1);
std::cout << "Maximum of 3 and 7: " << maxInt << std::endl;
std::cout << "Maximum of 4.5 and 2.1: " << maxDouble << std::endl;
return 0;
}
Template Class
#include <iostream>
// Template class representing a Pair of values
template <typename T1, typename T2>
class Pair {
public:
T1 first;
T2 second;
// Constructor
Pair(T1 f, T2 s) : first(f), second(s) {}
};
int main() {
// Using the template class with different types
Pair<int, double> myPair(3, 4.5);
std::cout << "Pair - First: " << myPair.first << ", Second: " << myPair.second << std::endl;
return 0;
}
The Pair
template class represents a pair of values. The types of the two values (T1
and T2
) are template parameters. The class is then used with int
and double
types.
Code Challenge
Create a generic calculator program that supports basic arithmetic operations (addition, subtraction, multiplication, and division) for different data types.
Implement a template class calledCalculator
.
Loading...
> code result goes here