zettelkasten

Function Amp Class Templates

Last updated: 1/9/2025

Function Templates

Function templates are SUPER useful, they are useful when you have a function that can be applied to multiple types of data, and you don't want to re-write the function definition.

For example, if you wanted to write a function that compares two values, that function can be applied to all integers, doubles, chars, etc. and b/c we're lazy we don't want to have to write that out three separate times, this is where templates come in!

cpp
template <typename T>
T CompareValues(T a, T b){/* implementation */}

One important difference is that the definition of the function template MUST be written in the header file!!! (This is because of how compilation-and-execution-in-c works).

In order to invoke the function you can do as so:

cpp
int bigger = CompareValues<int>(int1, int2);

But the compiler can also deduce what the type T should be if everywhere that the type should be T has the same type. Ex:

cpp
double bigger = CompareValues(double1, double2);

This inference, however, will not happen if the types don't match and will result in an error.

Class Templates

Similar to function templates, class templates are used when you want a generic version of a class. An example is

cpp
// Stack.h
template <typename T>
class Stack{
public:
Stack& add(T item);
private:
std::vector<T> items;
};
template <typename T>
Stack& Stack::add(T item){
items.push_back(item);
return *this;
}
// main.cc
Stack s;
s.add(1);
s.add(3);
// s.add(3.2) <--- ERROR

See Also

  1. [[c]]