Hacker News new | ask | show | jobs
by cubaia 3560 days ago
I think templates get a bad reputation because in practice many uses of templates are not appropriate.

Too many clever people saw 3 repetitions of a pattern and decided to show case every template trick to create a "generic library" that is compile-time optimized, usually to solve a problem that doesn't exist.

Multiply that many times through the course of a project and you end up with code that seems to try to maximizes job security.

1 comments

Any abstraction can be taken too far, but I think templates tend to be particularly attractive because it is both mentally challenging and can easily produce huge volumes of code. It makes those who enjoy overcomplicating things feel productive. The same can be said of things like design patterns and "OOP extremism", but templates give that extra flair of "expertise".

On the other hand, I'm the exact opposite. I hate overly complex solutions to intrinsically simple problems. I use abstractions sparingly and only when they reduce overall, not just local complexity. Sometimes moving down a level of abstraction or two will yield a better solution. Write simple code. Focus on programming and solving the problem, not metaprogramming and the metaproblem. If you're spending weeks to write (and debug!) a huge "generic solution" spanning a dozen files and several thousand lines of code which someone else could do in an hour with a few dozen lines of code in one file, I don't think that's being clever at all. I've personally experienced this, being that "someone else".

The C++ purists will probably find this repulsive, but in some cases a macro will be the far simpler solution. What templates can do are not a strict superset of what the preprocessor can do.

"All problems in computer science can be solved by another level of indirection, except those caused by too many levels of indirection."

I'm quite fluent in both template metaprogramming and preprocessor metaprogramming. The former is significantly easier to write and understand, and, most importantly, to debug.

There are some things that can't be done via templates and you have to resort to the preprocessor, but for everything else, I will choose templates.

I do agree that premature generalization, in all forms, is often the root of all evil.

> What templates can do are not a strict superset of what the preprocessor can do.

C++ templates are Turing complete, but the C preprocessor is not.