Small Stab at C++ Templates


Never really had a chance to play around with C++ Templates, since most work during my undergrad didn’t require it and I had found that most companies avoided writing any templates themselves (at most only using the STL ones).

I noticed at my current job that they had implemented a few times their own LinkList classes since they are not including/using the STL. Looking over some of the implementations (some a bit more generic than others using void pointers) wanted me to try and write my own LinkList template class.

Although most would quickly deem it worthless of an attempt and clearly trivial, writing the class helped solidify a few deeper understandings for me in C++.

  • The use of the keyword typename. Since C++ templates are generated at compile time, they are done in a multipass fashion. During the first pass, certain types are not yet defined however can be referenced, i.e. LinkList::Iterator. In order to tell the compiler that Iterator is a type and not a variable, the keyword typename is used.
  • Proper const and reference correctness. There were some additional nuances that I was unaware of when working with const types. For instance, when returning a reference via an inspection method (const method), the return type must be const as well.
  • You can actually some pretty crazy shit with templates, namely metaprogramming.
  • The STL is pretty crazy and I take it for granted in most software projects I do. I was scratching my head for a bit on just how I wanted to implement my Iterator…

The STL is pretty crazy and I take it for granted in most software projects I do.

Here’s my stab…

Leave a Reply

Your email address will not be published. Required fields are marked *