Template meta-programming can be a very interesting, complicated topic (anything “meta” is very interesting, after all). We’ll keep it very simple in this class.
The idea behind template meta-programming is that we want to use a special language on top of C++ that generates C++ code. This “template meta-language” is itself a full programming language, but we’ll just use the simplest pieces. Our use of template meta-programming will be limited to generating classes and functions that work on any type of object.
Important note: Template classes and functions must have their
full implementations in the header file, not an external
file. This is because template classes and functions cannot be
compiled in a generic way, so we cannot produce a
.o file that has
compiled but generic functions/methods.
Generic linked lists
Think back to our linked lists. Let’s say we have a linked list class:
LinkedList class was fully implemented, we would be able to do
things like this:
But this is quite unfortunate! That linked list class only stores
values. There are more things in heaven and earth than can be represented as
double values. (Well, not really, since representations don’t matter,
theoretically. But in practice, they do.)
We want to create a single linked list class that can store any (single) type of value. We will not have the option to create a linked list that can store varying types of values (e.g. a linked list with strings, doubles, ints, and so on all in the same list will not be possible). But, it would be nice to write one linked list class that can store strings, or in another instance integers, or whatever. Template meta-programming allows us to do this.
Creating a templated class
All you have to change about the linked list class above in order to support making a linked list with a (single) arbitrary type is the following:
Now, to use such a “generic linked list,” when we create a
main() function we have to say what type we’re using (
T will become
whatever that type is).
Ok, that’s still
double values in our linked list. Let’s put strings inside
The linked list that stores string values is the same class as above. We can create two linked lists storing different types of values, if we wish:
That feeling of elation that you must have is the feeling of freeing yourself
from strong typing. You didn’t really free yourself; the types are all still
string, etc.). But it’s close enough (we don’t need much to
Another example: Template specialization
This example is borrowed from cplusplus.com. It shows how we can “specialize” a template class by writing another class with a specific type for the template type, and even add new methods that that specialized class.
You can use templates on functions, too, and not just classes. Example from cppreference.com