Building Solid Template Classes – Stick to Headers

DKit Laboratory

Today I was starting to compile my latest addition to DKit - the UDP receiver that's a source of datagrams in the DKit sense. This is really just the first step of many to get the exchange feeds re-written into DKit in a far better way than I had recently done. The second time is always better, and the third better still.

So I had built the source and sink template classes with headers and implementation files. This, it turns out, really isn't such a hot idea. Because the templates are expanded at compile time, it's not possible to compile the source once, and then use it over and over again. I should have know this, but it wasn't smacking me in the face until I started to try and compile the UDP receiver and it was talking about missing implementations of the source::~source() for the specialization (datagram *).

Then it was instantly clear - I needed to keep everything in headers so that they could be expanded and built as needed, at compile time. Thankfully, there wasn't a lot of work to do - just move the code from the implementation file to the header and drop the implementation files from the directory and Makefile. It didn't take long, but it was clear that this was the right thing to do. The compiles started working, and things progressed nicely.

Not done, that's for sure, as I still need to throw in the async reader method to the UDP receiver, and then I can pull in that pool of datagrams and we should be in good shape. But it's still a little bit of work.

But it's nice to know that template programming is not only tricky and convoluted, it's also like Java code - all in one file. OK… that's a stretch, even for me. 🙂