In this tutorial, our main goal is to demonstrate how to create function and class templates in C++. By the end of this tutorial, you will understand what function and class templates are, why we use them, and how to use them effectively in your code.
Prerequisites include:
- A basic understanding of C++ syntax
- Familiarity with functions and classes in C++
Templates are powerful features in C++ which allows you to write generic programs. In simple terms, you can create a function or a class to work with any data type.
A function template starts with the keyword template
followed by template parameters enclosed in < >
.
Example:
template <typename T>
T getMax(T x, T y) {
return (x > y)? x : y;
}
In the above example, typename T
is a template argument which is a placeholder for the data type of variables.
Like function templates, class templates are used to create class functions that can work with any data type.
Example:
template <class T>
class MyClass {
T value;
public:
MyClass (T val) {value = val;}
T getValue() {return value;}
};
In the above example, class T
is a placeholder for the data type of variables.
#include<iostream>
using namespace std;
// function template
template <typename T>
T getMax(T x, T y) {
return (x > y)? x : y;
}
int main() {
cout << getMax<int>(3, 7); // calling function with integer
cout << getMax<double>(3.0, 7.0); // calling function with double
return 0;
}
Here, getMax<int>(3, 7)
will return 7 and getMax<double>(3.0, 7.0)
will return 7.0.
#include<iostream>
using namespace std;
// class template
template <class T>
class MyClass {
T value;
public:
MyClass (T val) {value = val;}
T getValue() {return value;}
};
int main() {
MyClass<int> myObj(100);
cout << myObj.getValue();
return 0;
}
In the above code, MyClass<int> myObj(100);
creates an object of MyClass with integer type and cout << myObj.getValue();
will output 100.
In this tutorial, we have learned about function and class templates in C++. We have discussed how to create them and why they are useful in making the code more flexible and reusable.
To continue learning, you should try to use templates in your own code and see how they can make your life easier. You can also read more about templates in the C++ documentation.
Solutions:
1.
template <typename T>
T getMin(T x, T y, T z) {
return min({x, y, z});
}
In this function template, we use the min
function from the standard library to find the minimum of three variables.
2.
template <class T>
class Stack {
private:
vector<T> elements;
public:
void push(T const& element) { elements.push_back(element); }
T top() const {
if (elements.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
return elements.back();
}
void pop() {
if (elements.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
}
elements.pop_back();
}
};
In this class template, we create a 'Stack' data structure that can handle any data type.