Tuesday 12 November 2013

More on Templates

Today in OOP344 we went over the basics for class templates. For review here is a picture taken in class on the rules of creating a class template:

                                            Fardad's beautiful handwriting 

According to Fardad, we will not be learning more advance template concepts such as template specialization and partial specialization. That is unfortunate to hear as templates are conceptually complex and interesting. From what I've learned so far we can create specialized templates which means we can create a special case scenarios for certain types (instead of a previously coded general template) by doing something like this:

template<>   // no template parameters, compiler looks ahead (general template must exist)
class Node<bool>{ ... }; // matches previously defined template for class Node
                                         // uses this one if type is bool

We can also partially specialize a template like this:

template <typename A, typename B> // General template
class Node{ ... };

template<typename A>     // Partially specialized template
class Node<A, A*>{ ... };    // Explicitly declaring additional parameters

It seems that by providing additional parameters after the class name, we create additional rules for using this template. The compiler will always use the best fit template. For the above example, we still have generic type A, but in order to use this template, we need to pass a type along with a pointer of the same type ie. A<int, int*> a;.

0 comments:

Post a Comment