Table of Contents

1. What are templates?

1.1. Before Templates

ogl.png

Figure 1: A rendering of a simple 3D scene built from triangles and quads, rendered with OpenGL.

Templates don't exist in C++'s precursor, C. Because of this, if you had a function like - for example - SumTwoNumbers - that you wanted to work with different data types, you would have to define different functions for each version. C also doesn't have function overloading, so they would have to have different names as well.

As a real-world example, OpenGL is a cross-platform graphics library that can be used to create 3D graphics. OpenGL was written in C, and you could tell it a set of vertices to draw in order to create one polygon or quad or other shape. There were different functions you could use to define points (vertices) in a shape, like:

  • glVertex2f( 0, 0 );
  • glVertex3f( 0, 0, 0 );

And, in particular, there are a bunch of "glVertex" functions: glVertex2d, glVertex2dv, glVertex2f, glVertex2fv, glVertex2i, and so on… (Don't you wish you were programming in C?)

Templates are a strategy we can use to cut down on… A. Duplicate code / B. Easy-to-read code / C. Fanatical C programmers reading our code

1.2. Using Templates

template.png

With C++ and other languages like C# and Java, we can now use Templates with our functions and classes. A Template allows us to specify a placeholder for a data type which will be filled in later.

In the C++ Standard Template Library, there are objects like the vector that is essentially a dynamic array, but it can store any data type - we just have to tell it what it's storing when we declare a vector object:

vector<int> listOfQuantities;
vector<float> listOfPrices;
vector<string> listOfNames;

We can also define our own functions and even classes with templated functions and member variables ourselves, leading to much more reusable code.

2. Templated functions

We can write a standalone function with templated parameters or a templated return type or both. For example, here's a simple function to add two items together:

template <typename T>
T Sum( T numA, T numB )
{
  return numA + numB;
}

This function can be called with any data type, so long as the data type has the + operator defined for it - so, if it were a custom class you wrote, you would have to overload the operator+ function.

What this means is that we can call Sum with integers and floats, but also with someting like a string, since strings use the + operator to combine two strings together.

int main()
{
  int intA = 4, intB = 6;
  float floatA = 3.9, floatB = 2.5;
  string strA = "alpha", strB = "bet";

  cout << intA << " + " << intB
      << " = " << Sum( intA, intB ) << endl;

  cout << floatA << " + " << floatB
      << " = " << Sum( floatA, floatB ) << endl;

  cout << strA << " + " << strB
      << " = " << Sum( strA, strB ) << endl;
}

Program output:

4 + 6 = 10
3.9 + 2.5 = 6.4
alpha + bet = alphabet

A templated standalone function that uses the template placeholder type T as a parameter looks like…?

3. Templated classes

More frequently, you will be using templates to create classes for data structures that can store any kind of data. The C++ Standard Template Library has data structures like vector, list, and map, but we can also write our own.

When creating our templated class, there are a few things to keep in mind:

  1. We need to use template <typename T> at the beginning of the class declaration.
  2. Method definitions must be in the header file - in this case, we won't be putting the method definitions in a separate .cpp file. You can either define the functions inside the class declaration, or immediately after it.
  3. Method definitions also need to be prefixed with template <typename T>.

If you try to create a "TemplatedArray.h" file and a "TemplatedArray.cpp" file and put your method definitions in the .cpp file, then you're going to get compile errors:

undefined-reference.png

You might think, "Well, that's weird." - and yes, it is. C++ is a strange language with weird behaviors. In this case in particular, you can read about why this is for templates here: https://isocpp.org/wiki/faq/templates%5C#templates-defn-vs-decl

In short, the template command is used to generate classes, and while our class declaration looks normal, this is actually special code that is just telling the compiler how it's going to generate a family of classes. Because of this, the compiler needs to see the function definitions as well.

3.1. Example templated class

Here's a small example of a templated class declaration.

Class declaration (.h file):

template <typename T>
class CLASSNAME
{
  public:
  void Setup( T PARAM1, int PARAM2 );

  private:
  T VARNAME1;
  int VARNAME2;
};

If the class uses a templated type somewhere within it, it needs to

have the template <typename T> specified above the class name. Some templated classes may have member variables with T as their data types, but this isn't a requirement.

Templated function declarations go in which file type? .h / .cpp

Templated function definitions go in which file type? .h / .cpp

The declaration of a templated class looks like…?

The definition of a templated class' member function looks like…?

Function definitions (also in .h file)

template <typename T>
void CLASSNAME<T>::Setup( T PARAM1, int PARAM2 )
{
  this->VARNAME1 = PARAM1;
  this->VARNAME2 = PARAM2;
}

The templated functions' definitions must also go in the header (.h) file. This is how the definition would look if you're defining it beneath the class declaration.

Instantiating the templated class (main.cpp example)

int main()
{
  CLASSNAME<string> obj1; // PARAM1 will be a string
  CLASSNAME<float> obj2; // PARAM1 will be a float

  // Calling the templated function:
  obj1.Setup( "Test", 100 );
  obj2.Setup( 2.99, 50 );

  return 0;
}

When declaring an object variable whose data type is a templated class you need to specify the data type to fill into the T placeholder. This part goes within angle brackets < >.

Declaring an object whose data type is a templated class will look like…?

Author: RachelWil

Created: 2026-10-14 Wed 11:13

Validate