Hacker News new | past | comments | ask | show | jobs | submit login

IMHO if you're messing with templates in C++ you've probably over-engineered your solution.

There are a few cases where they can make sense, like in the standard library, but most of the time without them your code will be cleaner and you'll never actually run into the case where they pay off.




I've run into cases where templates pay off once or twice. I was once able to refactor 1000+ lines of code into about 150 lines using a template class. However, I've tried more than once to learn "advanced" meta-programming techniques, and I've yet to find a use case that makes any sense.


I wrote a library a few years back to do in-place non-square transposition in the GPU register file. The algorithm had a lot of math that needed to be computed for every size matrix. I wrote it in C++03, before any constexpr, so the metaprogramming is intense. One of these days I'll rewrite it in C++20 and most of the code will go away. This code is still in use by the way.

https://github.com/bryancatanzaro/trove


If you need compile-time stuff that constexpr can't do, then you have little choice. Of course, in reality, its very rare that you "need" compile-time stuff.


It is not rare at all to want your program to handle generic output. Templates might not be the cleanest syntax but they do address a real need.


I wasn’t referring to genetics or saying that templates aren’t necessary or useful, or even that they aren’t common. Those uses of templates are relatively straightforward most of the time. Where templates, IMHO, become unwieldy is when trying to compute things at compile time. In many cases constexpr works here, but my point was that the remaining cases are relatively rare, certainly when you need it (as opposed to just wanting it, eg for performance).




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: