Function Template and Class Template in C++
C++ stands out as a strong and independent language that keeps it simple and easy to understand. One thing that makes C++ a versatile language is its love and support for the templates. Templates help you write code that will write different types of data without losing safety or speed.
There can be a lot of templates, and this tutorial will focus mainly on two types of templates: function templates and class templates. We will dive deeper into the concepts and learn about them.
Function Templates
Function templates are a list or structure of elements to help us write a function for our data or element. It will help us create such functions that will help us work with different types of tasks. This entire process makes our code easier and very good when managing our code. When we want to create a function template, we have to simply use the template keyword followed by the simple data type and angular brackets. When we talk about the inside functionality of the template, you can simply declare the variables and start defining the operations they would perform.
Class Templates
When we talk about class templates, they are generally blueprints for different types of boxes. Just as we can create different boxes for storing toys, cartoons and everything else, very similarly, class templates are used to create a class where we can work or hold different types of data. They are very useful when creating or working with lists or sorting because in cases in these, you don't want to limit your capabilities to one data type and want it to work for all types of data.
Advantages of Templates
Function Templates offer several advantages in C++ programming: -
- Code Reusability
Function templates allow for the code reusability feature, which means that we can simply create a function one time in our whole code, and whenever we want to use that function in our code again, instead of writing it again and again, we can just simply declare it once and we can just pass arguments into the code whenever required.
- Type Safety
Function templates also help us ensure that we only use the right form of data type while working with them. It's basically like double-checking everything while making a dish, whether or not we have used the right kind of ingredients.
- Performance
They ensure they are sorted out and well-versed when defining and solving anything. They don't have to constantly check what type of data type they are dealing with. They do these things fast, so they are fast and reliable.
- Flexibility
Function templates help us create functions that can handle any data type, and they don't even care what data we are passing. They already know their steps, and thus, they become highly reliable when working with them.
Class templates
This section will examine the advantages and disadvantages of class templates.
- Using Code Again (Reusability)
Class templates help us create classes that work well with all kinds of data. We don't have to create specific classes for each type of data repeatedly. This makes it easier for anyone to understand our code and makes our code very easy to understand.
- Safety
Just as you saw in the function template, a similar class template also ensures that whatever code we define within it is safe to use. The system automatically checks on us whether we are using the right kind of data to ensure that we are less prone to errors and making mistakes.
- Being Flexible
Class templates highly promote flexibility, as with the help of these, we can create both system designs and data structures and algorithms. They are very useful when it comes to their usage. They can easily work with different types of data without slowing our computers down, which simply means that we can create versatile things without taking much pressure.
Example 1:
#include <iostream>
// Function Template: Generic function to find the maximum of two elements
template<typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
// Class Template: Generic class for a Pair
template<typename T1, typename T2>
class Pair {
private:
T1 first;
T2 second;
public:
Pair(T1 f, T2 s) : first(f), second(s) {}
T1 getFirst() const {
return first;
}
T2 getSecond() const {
return second;
}
};
int main() {
// Using function template
std::cout << "Maximum of 100 and 129 is: " << max(100, 129) << std::endl;
std::cout << "Maximum of 10.5 and 19.78 is: " << max(10.5, 19.78) << std::endl;
// Using class template
Pair<int, double> pair1(1, 0.14);
Pair<std::string, char> pair2("Hello", 'C');
std::cout << "Pair 1: " << pair1.getFirst() << ", " << pair1.getSecond() << std::endl;
std::cout << "Pair 2: " << pair2.getFirst() << ", " << pair2.getSecond() << std::endl;
return 0;
}
Output:
![Function Template and Class Template in C++](https://static.tutorialandexample.com/cpp/function-template-and-class-template-in-cpp1.png)
Example 2:
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
// Function Template: Generic function to find the maximum of two elements
template<typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
// Class Template: Generic class for a Pair
template<typename T1, typename T2>
class Pair {
private:
T1 first;
T2 second;
public:
Pair(T1 f, T2 s) : first(f), second(s) {}
T1 getFirst() const {
return first;
}
T2 getSecond() const {
return second;
}
};
// Class Template: Generic Stack
template<typename T>
class Stack {
private:
std::vector<T> elements;
public:
void push(T item) {
elements.push_back(item);
}
T pop() {
if (elements.empty()) {
std::cerr << "Stack is empty!" << std::endl;
exit(1);
}
T item = elements.back();
elements.pop_back();
return item;
}
bool isEmpty() const {
return elements.empty();
}
};
int main() {
// Using function template
std::cout << "Maximum of 13 and 79 is: " << max(13, 79) << std::endl;
std::cout << "Maximum of 10.5 and 19.78 is: " << max(10.5, 19.78) << std::endl;
// Using class template Pair
Pair<int, double> pair1(0.9, 0.1);
Pair<std::string, char> pair2("Hello", 'T');
std::cout << "Pair 1: " << pair1.getFirst() << ", " << pair1.getSecond() << std::endl;
std::cout << "Pair 2: " << pair2.getFirst() << ", " << pair2.getSecond() << std::endl;
// Using class template Stack
Stack<int> intStack;
intStack.push(8);
intStack.push(2);
intStack.push(76);
while (!intStack.isEmpty()) {
std::cout << "Popped: " << intStack.pop() << std::endl;
}
Stack<std::string> stringStack;
stringStack.push("hey");
stringStack.push("my name");
stringStack.push("is");
while (!stringStack.isEmpty()) {
std::cout << "Popped: " << stringStack.pop() << std::endl;
}
return 0;
}
Output:
![Function Template and Class Template in C++](https://static.tutorialandexample.com/cpp/function-template-and-class-template-in-cpp2.png)
Example 3
#include <iostream>
// Node Template: Represents a single node in the linked list
template<typename T>
struct Node {
T data;
Node<T>* next;
Node(T val) : data(val), next(nullptr) {}
};
// Class Template: Generic Linked List
template<typename T>
class LinkedList {
private:
Node<T>* head;
public:
LinkedList() : head(nullptr) {}
~LinkedList() {
while (head) {
Node<T>* temp = head;
head = head->next;
delete temp;
}
}
void insert(T val) {
Node<T>* newNode = new Node<T>(val);
if (!head) {
head = newNode;
} else {
Node<T>* current = head;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
}
void display() const {
Node<T>* current = head;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
bool isEmpty() const {
return head == nullptr;
}
// Function to reverse the linked list
void reverse() {
Node<T>* prev = nullptr;
Node<T>* current = head;
Node<T>* next = nullptr;
while (current != nullptr) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}
};
int main() {
// Creating a linked list of integers
LinkedList<int> intList;
intList.insert(50);
intList.insert(200);
intList.insert(3000000);
std::cout << "Original List: ";
intList.display();
// Reverse the list and display
intList.reverse();
std::cout << "Reversed List: ";
intList.display();
// Creating a linked list of strings
LinkedList<std::string> stringList;
stringList.insert("Hello");
stringList.insert("Everyone");
stringList.insert("!");
std::cout << "Original String List: ";
stringList.display();
// Reverse the string list and display
stringList.reverse();
std::cout << "Reversed String List: ";
stringList.display();
return 0;
}
Output:
![Function Template and Class Template in C++](https://static.tutorialandexample.com/cpp/function-template-and-class-template-in-cpp3.png)
Example 4
#include <iostream>
// Function Template: Generic function to find the maximum of two elements
template<typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
std::cout << "Maximum of 98 and 777 is: " << max(98, 777) << std::endl;
std::cout << "Maximum of 46.5 and 9.888888 is: " << max(46.5, 9.888888) << std::endl;
return 0;
}
Output:
![Function Template and Class Template in C++](https://static.tutorialandexample.com/cpp/function-template-and-class-template-in-cpp4.png)
Conclusion
In conclusion, function templates and class templates, are important components in the C++ programming language. They make our code flexible with each passing day and keep it easier to maintain and run efficiently, which makes it versatile in today's time. If you want to be good at programming, understanding about the concept of templates is essential.