C++ / C++ Templates and STL
Creating Function and Class Templates
In this tutorial, you will learn how to create your own function and class templates in C++. This knowledge will allow you to write more flexible and reusable code.
Section overview
5 resourcesIntroduces templates, generic programming, and the Standard Template Library (STL).
1. Introduction
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++
2. Step-by-Step Guide
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.
Function Templates
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.
Class Templates
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.
3. Code Examples
Function Template
#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.
Class Template
#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.
4. Summary
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.
5. Practice Exercises
- Create a function template to find the minimum of three numbers.
- Create a class template for a 'Stack' data structure.
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.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article