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.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Introduces 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

  1. Create a function template to find the minimum of three numbers.
  2. 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help