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

> you can often solve the problem with more verbose, but simpler code.

Sometimes. Other times, templates are simpler.

> I have the impression that people use it because they can

I think people use template metaprogramming because they see it in standard library, but they don’t understand the requirements for C++ STL were very different from the requirements of the code they’re personally developing.

I use C++ templates for following reasons.

1. For data structures such as custom containers.

2. For zero-overhead polymorphism. E.g. when I write algorithms that must work exactly same way with floats and doubles, or with char and wchar_t strings. Or for zero-overhead lambdas, putting them in std::function causes virtual function call overhead, lambdas are usually inlined.

3. For zero-overhead constants. There’s constexpr in modern C++, also modern compilers are good at propagating constants, but still a template argument is more reliable.

When I need complex metaprogramming, I often use other tools to generate the C++ code I need. On Windows it’s usually T4 templates with C# inside them, on Linux usually python. Compared to C++ templates, both T4 and python have much better support in IDEs (visual studio / PyCharm), including debuggers.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: