Friday, February 27, 2009

Templates

In a few of the recent lectures, we've covered function templates and the use of templates for defining new classes. In addition to the lectures, the latest reading assignment from the book (Ch 18) also covers templates (or generics as they're more generally known). For the most part, I haven't really used this to my advantage in the past, but after seeing them in use, it really seems like they can be pretty useful. They do have their drawbacks of course. It may be a little confusing to try and figure out what is going on exactly. What is going on may not be what the user intends. For example, as the lecture on Function Templates demonstrated, making calls to Function Templates can be somewhat confusing (EX: my_max ("stu", "pqr") completely ignores the non-template function that would make it work, but my_max("abc", "def") doesn't). But as shown in the example, it is nice to have a "single" function called my_max that can work with a variety of data types.

Even better is the use of templates for classes. When were producing the code for the stack in class, I thought we were limiting it to just ints (and initially, we were). But by using templates, we quickly allowed the stack to store basically any type T, as long as T supported the various operations stack used. Even further, you could basically pass in a value for the maximum size of the stack using the template syntax. This almost doesn't seem much different that simply passing in the size as an argument, but if there is only a default constructor (which takes no arguments), the max size of the stack can still provided as shown in the example (Stack x;).

The book covers some of the more confusing aspects that might arise when using templates. For example, what is the relationship between two objects that use the same template, but have different types? For example, Stack vs Stack. Or what happens if you extend a templated class in a new class, which doesn't use templates? Things can get a little confusing once you start extending these classes.

In any case, they seem like a pretty nice feature of C++ (and other languages), and I'd like to explore their functionality in the future.

No comments:

Post a Comment