by flohofwoe · 12y ago · 0 comments
- they can make interfaces more simple by using template methods/functions (have a single method which is specialized by the compiler, instead of polluting the API with 20 slightly different methods which only differ by the argument type)
- they can enable a coding style which 'looks and feels' almost dynamic without loosing the strict type checks and optimization opportunities that a static type system provides
- they can help to keep related data close together in memory and minimize dynamic memory allocation (e.g. an array of structs instead of an array of pointers)
- the compiler has more optimization opportunities because it has more type information (vs. a more dynamic system where types are only known at runtime)
The tradeoff is of course that the compiler generates more (specialized) code, it breaks the simple rule that the amount of generated code grows linearly with the number of lines of code. On the other hand the compiler has a lot more type info to optimize the generated code. Still the programmer has to know what's happening under the hood so he can weigh the advantages against the disadvantages.
[edit: formatting]
There is actually a tremendous amount of value of precomputing a lot of work that is currently computed at runtime (the amount of wasted CPU in your typical C++ program, particularly at start time, is kind of crazy). It's just that the real hot spots in real world programs programs tend to revolve around runtime dynamic logic.
Exactly. Templates let you do compile-time duck typing. That's extremely useful in so many scenarios.