Tuesday, July 6, 2010

C++ Templates

Today I was working on some standard C++ data structures for a CS class. I wanted to make them generic so that they could be used to hold any primitive or object. C++ offers this flexibility with templates. I found some simple tutorials and went at it. When I was finished, I couldn’t get them to work. I kept getting an undefined reference error during the linking process. What made it the most challenging is that everything was syntactically correct. I had to scour the internet to find the answer. It turns out that with C++ templates, the implementation must be included in the header file. There are a few ways to accomplish this. First, is to use the “export” keyword just before declaring the template. This option isn’t supported by most compilers. I have been using g++ which does not support this feature. Second, the .cpp file can be #included at the end of the .h file. I didn’t prefer that approach. Third, the implementation can be copied to the end of the header file. This is essentially the same as the second option. The fourth option is to simply define each method as soon as it is declared. Any of these four options will essentially merge the implementation and header files directly or indirectly. I took the last option. Once my files were merged, my data structures worked perfectly. Again, it is always the fine details that create the biggest problems.