Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Generic Programming - Simple C++ Templates

David Egan

C++ is a strongly typed language - all variables must have a specific type, either explicitly defined by the programmer or inferred during compilation. However, function operations are often identical regardless of the data type being operated on. For example, the body of a function that sums two numbers will be identical for both int and float types.

C++ allows generic functions to be created using templates. This means that the function can work on many different data types without being rewritten for each one. The template generates an ordinary type or function when it is compiled, based on the arguments supplied to the template.

Simple Template

Simple template definition where all input parameters and return variables are of the same type:

// Define the template
template <typename T>
T genericSumTwo (T a, T b)
    return a + b;

int intA = 2;
int intB = 2;
float floatA = 2.22;
float floatB = 2.44;

// Use the template with `int` type
std::cout << genericSumTwo(intA, intB) << std::endl;
/* Outputs 4 */

// Use the template with `float` type
std::cout << genericSumTwo(floatA, floatB) << std::endl;
/* Outputs: 4.66 */

Template with Different Data Types Input

Templates can accept different data types - with the return data type specified in the template definition:

// Template accepts multiple variable types
template <typename T, typename U>
T getBigger(T input1, U input2)
    if (input1 > input2) {
        return input1;
    return input2;

// Usage
float A = 2.22;
int B = 1;
std::cout << getBigger(A, B) << std::endl;
/* Returns result as a float: 2.22 */

This definition allows different variable types as input parameters, and specifies that the return type will be the same as the type of the first supplied parameter (in this case, T).


comments powered by Disqus