Templates in CPP

Understanding Templates in C++ Programming Language: Building for Generality

Templates form the bedrock of generic programming, a technique that involves crafting code that is not tied to any par

ticular data type. A template serves as a blueprint or formula for constructing a generic class or function. The constructs found in the C++ Standard Library, such as iterators and algorithms, are products of generic programming and are built upon the foundation of templates. Templates in C++ provide an overview of a powerful feature that allows for the creation of generic classes and functions.

While there’s a single definition for each container (e.g., vector), templates allow you to define various instances of containers for different data types, such as vector<int> or vector<string>.

Templates find application in both function and class definitions, providing a versatile tool for enhancing code reusability and flexibility.

Function Templates

The basic structure of a template function is demonstrated here:

template <class type> ret-type func-name(parameter list) {
   // function body
}

In this construct, type acts as a placeholder representing the data type used by the function. This placeholder can be employed within the function’s definition.

Here’s an example of a function template that returns the maximum of two values:

#include <iostream>
#include <string>

using namespace std;

template <typename T>
inline T const& Max(T const& a, T const& b) {
   return a < b ? b : a;
}

int main() {
   int i = 39;
   int j = 20;
   cout << "Max(i, j): " << Max(i, j) << endl;

   double f1 = 13.5;
   double f2 = 20.7;
   cout << "Max(f1, f2): " << Max(f1, f2) << endl;

   string s1 = "Hello";
   string s2 = "World";
   cout << "Max(s1, s2): " << Max(s1, s2) << endl;

   return 0;
}

The result of executing this code would be:

Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World

Class Templates

Just as function templates provide generic functionality for functions, class templates do the same for classes. The general pattern for declaring a generic class is:

template <class type> class class-name {
   // class body
}

In this pattern, type is a placeholder that will be replaced with the actual data type when the class is instantiated. Multiple generic data types can be defined by using a comma-separated list.

Here’s an example of a class template named Stack that implements generic methods for pushing and popping elements:

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>

using namespace std;

template <class T>
class Stack {
private:
    vector<T> elems; // elements

public:
    void push(T const&);  // push element
    void pop();           // pop element
    T top() const;        // return top element

    bool empty() const {  // return true if empty
        return elems.empty();
    }
};

template <class T>
void Stack<T>::push(T const& elem) {
    elems.push_back(elem);
}

template <class T>
void Stack<T>::pop() {
    if (elems.empty()) {
        throw out_of_range("Stack<>::pop(): empty stack");
    }
    elems.pop_back();
}

template <class T>
T Stack<T>::top() const {
    if (elems.empty()) {
        throw out_of_range("Stack<>::top(): empty stack");
    }
    return elems.back();
}

int main() {
    try {
        Stack<int> intStack;       // stack of ints
        Stack<string> stringStack; // stack of strings

        intStack.push(7);
        cout << intStack.top() << endl;

        stringStack.push("hello");
        cout << stringStack.top() << std::endl;
        stringStack.pop();
        stringStack.pop();
    } catch (exception const& ex) {
        cerr << "Exception: " << ex.what() << endl;
        return -1;
    }
}

Upon execution, the output would be:

7
hello
Exception: Stack<>::pop(): empty stack

Templates empower programmers to write code that transcends specific data types, enabling code reuse and versatility. The ability to craft generic functions and classes contributes to building robust and adaptable programs.


Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading