Starting with version 1.18, C++ has added support for templates, which are similar to generics in other languages.
As an example of a template function, SlicesIndex takes a vector of any comparable type and an element of that type and returns the index of the first occurrence of v in s, or -1 if not present. The std::vector and std::equal_to are used to achieve this functionality.
As an example of a template class, List is a singly-linked list with values of any type.
Here’s how we can use these template functions and classes:
When compiling and running this program, you should see:
In C++, templates are a compile-time feature, which means that the compiler generates specialized code for each type the template is used with. This can lead to better performance compared to runtime polymorphism, but it can also increase compile times and code size.