C++ templates

C++ templates allow us to define functions and classes that work with generic types. This allows a function or a class to accept any type, and it only has to be written once. This is what we want. We want to define a single get/set function for components, and we'll template them to make them generic and flexible.

Let's take a look at a practical example of templates to get a better idea of how they actually work.

Using templates

Let's suppose that we require a function to add two numbers, and we want to support a range of types. To achieve this, we could declare a function for each type that we want to support, as follows:

int Add(int value1, int value2) { return value1 + value2; } double Add(double value1, double value2) { return value1, ...

Get Procedural Content Generation for C++ Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.