15. Templates

About this Tutorial –

Objectives –

This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.

Audience

Students who are new to object orientation (or programming) and need to learn C++.

Prerequisites

No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The C++ course covers these topics and more:

  • Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
  • Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
  • Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures

Download Solutions

CplusPlus tutorial

Quick Access


Overview

Estimated Time – 0.5 Hours

Lab 1: Template functions

Lab 1: Template functions
  1. The Need for Template Functions
    • As we saw earlier in the course, C++ supports function overloading
      • Multiple functions with the same intent
      • But taking different combinations of arguments
    • Imagine a situation where the implementation of overloaded functions is the same
      • Each has the same algorithm
      • But works with different types
        //Examples
        int minimum(int a, int b)
        {
         return a < b ? a : b; } double minimum(double a, double b) {  return a < b ? a : b; } Date minimum(Date a, Date b) {  return a < b ? a : b; }
  2. Introducing Template Functions
    • C++ supports the concept of template functions
      • Similar to generic methods in Java and C#
    • You can define a templated version of a function
      • Use a placeholder data type, rather than a specific data type
      • The compiler will automatically generate specifically-typed versions of the function, based on the calls in the client application
    • General syntax for a template function:
      • This example shows one type parameter
      • In general, you can define any number of type parameters
        template <typename type_name_placeholder>
        return_type function_name(params)
        {
         ...
        }
  3. Example Template Functions
    • Here are some examples of template functions
      • You typically implement template functions in a header file
      • Allows the compiler to generate specific versions of the function every time it detects a function call in the client code
        // Header
        template <ypename T>
        T minimum(const T & a, const T & b)
        {
         return a < b ? a : b; } template <typename T> T maximum(const T & a, const T & b) {  return a > b ? a : b;
        }
        // Cpp File
        #include "MyTemplates.h"
        ...
        int num1 = 100, num2 = 200;
        cout << minimum(num1, num2); Money money1(100.50), money2(200.75); cout << minimum(money1, money2);
  4. Overloading Template Functions
    • You can define overloaded versions of template functions
      • This can be handy, if used judiciously
Lab
  1. Defining a PriorityQueue class
    • In Visual Studio, create a new C++ project named TemplatesApp in the student folder
    • Define a template class named PriorityQueue with the following characteristics (hint: make use of the standard list<T> or vector<T> classes):
      • PriorityQueue allows the client application to add items "at the end"
        template <typename T>
        void PriorityQueue<T>::AddItem(T item_, int priority_)
        {
         queue.push_back(PriorityItem(item_,priority_));
         SortAccordingToPriority(); // You have to overload PriorityItem::operator< for this to work... }
      • View code file.
      • PriorityQueue allows the client application to remove items "from the front"
        template <typename T>
        void PriorityQueue<T>::RemoveItem()
        {
         SortAccordingToPriority();
         list::iterator iter = queue.begin();
         queue.erase(iter);
        }
      • View code file.
      • The complication is that the queue keeps items in a prioritised order. There will be 5 priorities (1, 2, 3, 4, 5) and the client specifies the priority when adding an item
        template <typename T>
        void PriorityQueue<T>::SortAccordingToPriority()
        {
         queue.sort();
        }
        template <typename T>
        void PriorityQueue<T>::PriorityItem::DisplayPriorityItem() const
        {
         cout << ToString(); }
      • View code file.
      • All "priority 1" items must be ahead of all "priority 2" items, etc...
      • When you add an item, it goes at the end of that priority section
      • Removal always favours priority 1, then priority 2, etc...
    • Test with various different types of data
      string str0 = "Hello0";
      string str1 = "Hello1";
      string str2 = "Hello2";
      string str3 = "Hello3";
      PriorityQueue strqueue;
      strqueue.AddItem(str0, 1);
      strqueue.AddItem(str1, 2);
      strqueue.AddItem(str2, 2);
      strqueue.AddItem(str3, 3);
      strqueue.DisplayQueue();
      strqueue.RemoveItem();
      strqueue.RemoveItem();
      strqueue.DisplayQueue();
      strqueue.AddItem(str1,2);
      strqueue.DisplayQueue();
      strqueue.AddItem(str2,2);
      strqueue.DisplayQueue();
    • View code file.

Lab 2: Template classes

Lab 2: Template classes
  1. The Need for Template Classes
    • The previous section showed how to define template functions
      • Allows a common algorithm to be implemented in a type-agnostic manner
    • C++ also allows you to define template classes
      • Allows a common set of related functionality to be implemented in a type-agnostic manner
      • Widely used in the C++ STL, e.g. list<string>
      • You can also define your own template classes
  2. Introducing Template Classes
    • General syntax for a template class:
      • This example shows one type parameter
      • In general, you can define any number of type parameters
        template
        class class_name
        {
         // Class members, expressed in terms of type_name_placeholder.
        };
  3. Defining a Template Class
    • Here's an example of a template class definition
      template <typename T>>
      class MyStack
      {
      private:
       vector<T> elems;
      public:
       MyStack();
       ~MyStack();
       void Push(const T &);
       void Pop();
       T  GetTopElement() const;
       bool IsEmpty() const;
      };
  4. Implementing a Template Class
    • Here's the first part of the implementation
      • Note that the methods are typically implementing in the header file
      • Note that each method is prefixed with the template syntax
        template <typename T>
        MyStack<T>::MyStack()
        {
         cout << "Hello from the constructor!" << endl; } template <typename T> MyStack<T>::~MyStack() {  cout << "Hello from the destructor!" << endl; }
      • Here's the remainder of the implementation
        template <typename T>
        void MyStack<T>::Push(const T & item)
        {
         elems.push_back(item);
        }
        template <typename T>
        void MyStack<T>::Pop()
        {
         if (elems.empty())
          throw out_of_range("Cannot pop from empty stack");
         elems.pop_back();
        }
        template <typename T>
        T MyStack<T>::GetTopElement() const
        {
         if (elems.empty())
          throw out_of_range("Cannot get top element in empty stack");
         return elems.back();
        }
        template <typename T>
        bool MyStack<T>::IsEmpty() const
        {
         return elems.empty();
        }
  5. Using a Template Class
    • In client code:
      • Create objects of a template class
      • Specify type parameters in object declarations
    • Example:
      MyStack<string> myStrings;
      myStrings.Push("Hello");
      myStrings.Push("Goodbye");
      myStrings.Pop();
      String top = myStrings.GetTopElement();
Lab
  1. Defining a MultiMap class
    • Define a template class named MultiMap with the following characteristics (hint: make use of the standard map<K,V> class):
      • Each entry in the multimap has a key (of some type) and a collection of values (of some specific type)
        map<K, list<V>> mapOfLists;
      • View code file.
      • When you "put" an item into a map, the key and value must be specified
      • If they key doesn't exist yet, insert a new key and give it the single value
        template <typename K, typename V>
        void MultiMap<K,V>::Put(const K& key_, const V& value_)
        {
         mapOfLists[key_].push_back(value_); // If it's empty it will add a new one, if not it will push it back on the list
        }
      • View code file.
      • If the key does exist already, append the new value at the end of the existing values for the key. In other words, each key can correspond to a collection of values
      • Implement functionality to put an item, get all keys, get all values for a specific key, remove a value for a key, remove all values for the key, and remove an item altogether
        template <typename K, typename V>
        void MultiMap<K,V>::DisplayAllKeys() const
        {
         map<K, list<V>>::const_iterator iter;
         for (iter = mapOfLists.begin(); iter != mapOfLists.end(); iter++)
         {
          cout << iter->first <<endl;  } }
      • View code file.
    • Test thoroughly
      string str0 = "Hello0";
      string str1 = "Hello1";
      string str2 = "Hello2";
      string str3 = "Hello3";
      cout << "You can \"Put\" a single anything..." <<endl;
      MultiMap<int, string> myMultiMap;
      myMultiMap.Put(0, str0);
      myMultiMap.Put(1, str1);
      myMultiMap.Put(1, str2);
      myMultiMap.Put(2, str3);
      myMultiMap.DisplayMap();
      cout << "\nor a collection of anythings..." <<endl;
      list<string> myStringCollection1;
      myStringCollection1.push_back(str0);
      myStringCollection1.push_back(str1);
      etc...
    • View code file.
  2. Well done! you have completed the C++courses.
    How do I get a TalkIT certificate for this course?

    1. Once you have subscribed, TalkIT can monitor some of your activity on the website. But as the tutorials are designed to allow you to work when you want, we do not know exactly when you have finished a course - So just email TalkIT with:
      • The date you have completed all the tutorials in the course
      • Include the title of the course
    2. TalkIT will then send you a TalkIT certificate for that course

 

Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top