Wednesday, January 26, 2005

C++ Templates

I don't like C++ templates for most things. Lots of people write about how cool C++ templates are and the neat things they can do. However every time I run into some template code somebody has written I get confused. I'm not smart enough to understand C++ templates. Templates fail "Tod's #1 Programming Philosophy":
 
    The simplest code is the best code.
 
Our Mac porting team took a function we had and made it a templated function. It originally took a void pointer to a packet and copied it to a queue. Now it takes a templated type instead. The old non-templated function would have taken less than 5 seconds for any programmer to understand. I looked at the new templated code with one of our smartest programmers and after 10 minutes gave up trying to figure out all the intricacies of what the function was doing.
 
Yesterday I was modifying some templated class so that it inlined better. This function showed up in VTune and I was surprised that it wasn't auto inlined. While working on this I got a 30+ line compiler error message about an error in my code. I enlisted the help of one of our other brilliant programmers to work through it with me. It took us about a 30 minutes to figure out what exactly was going on.
 
These two examples are pretty typical of my experiences with C++ templates. In theory land C++ templates are really elegant solutions for abstract algorithms. However, most of the time I see C++ templates they have created an overly-complicated solution. That's goes against my programming philosophy.