handmade.network » Forums » Templates for containers?
spectre1989
Joe Best-Rotheray
4 posts
#13689 Templates for containers?
1 week, 2 days ago

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
mmozeiko
Mārtiņš Možeiko
1520 posts
1 project
#13694 Templates for containers?
1 week, 2 days ago Edited by Mārtiņš Možeiko on Dec. 7, 2017, 6:52 p.m.

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.
spectre1989
Joe Best-Rotheray
4 posts
#13699 Templates for containers?
1 week, 1 day ago

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.
LaresYamoir
7 posts
#13701 Templates for containers?
1 week, 1 day ago

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.
marcc
Marc Costa
23 posts
#13702 Templates for containers?
1 week, 1 day ago

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.