Handmade Network»Forums
Joe Best-Rotheray
4 posts
Templates for containers?
Hi all,

I generally try to avoid templates so I don't bloat compile times, and particularly if I need something that would be complicated with templates I just roll my own meta-programming systems. But what about simple container types? Is there still a good argument against using templates for something along the lines of a vector or queue?

Cheers
Joe
Mārtiņš Možeiko
2559 posts / 2 projects
Templates for containers?
Edited by Mārtiņš Možeiko on
If you have been watching HandmadeHero, then you can see you can write and use containers perfectly fine without templates. Whenever Casey needs an array, list or hashtable, he just puts data structure and needed methods. The cool part about this approach is that you can write more efficient containers and operations on it. Often you need very specific behavior on containers. For example, sometimes you just need to add elements and never remove. Sometimes you want to cache removed elements and reuse them for next add operations. Etc. With templates this is harder to do. It will be super messy or just too generic which won't allow specific optimizations.
Joe Best-Rotheray
4 posts
Templates for containers?
I've only got as far as day 50ish so I haven't got that far yet! Surely the different container behaviours (e.g. add and never remove) would just be different templates? I'd also quite like to replace the allocation macro with a template, as macros tend to confuse the IDE and debugger more than templates in my experience. But again, not sure if this would be worse for compile times than a macro. Urgh, I dunno.
23 posts
Templates for containers?
I still use templates for very general containers. Like an array of a certain memory size that also has a size for valid elements in the container. So basically an array with max size and current size. Most of the time I start with a container for a specialized case and only if I see that I can use the exact same container for other data, I change the container to be templatized.
Marc Costa
65 posts
Templates for containers?
If you want to minimize the effect templates take on your compile times, you might be interested in this solution presented here: https://youtu.be/qYN6eduU06s?t=776.

In short, make containers that operate on data (an array of bytes, pass the size of the data type as parameter) and make template versions of the container that have very simple functions that serve as wrapper for the "non type explicit" container.