Why templates used?

I have read lesson 1 of the intermediate course “Programming with Haiku” including the PDF

I took the intermediate course because I know a bit of C++ and don’t want to start from the very beginning.

I wonder why a template is used!?

Greetingd
Peter

They are used and abused for a lot of things, because they happen to allow to essentially run code and precompute things at compile time.

Basically they are a much more powerful replacement for preprocessor macros in most cases.

2 Likes

I would say, both compiler-time code execution and preprocessor replacement are the abuse of templates.

They were introduced in C++ to make it possible to parametrize functions (methods, classes, enums, etc) by argument types not only by argument values.

As an immediate example, there are container classes, say list. This class functionality allows constructing, structural modification, iteration etc operations that are essentially the same for any type of list elements. That is why a single template class is sufficient for them. Still, because C++ is statically typed language, you cannot define a list implementation without knowing the type of its elements. And this type is a parameter of container template, e.g. list<int> is list of integers, list<string> is list of strings etc.

Couldn’t I operate with pointer casting?

Greetings
Peter

Only if the type being contained in the list is a pointer type. Templates can instantiate classes by value instead of by reference.

Templates are often used by game developers to avoid indirection overhead, particularly due to inheritance and VTables.

1 Like