I’m wondering about this question in the context of scripting.
The poll itself is at the bottom, of this post, so you’re encouraged to read the arguments and relevant comments first 😉
As a reminder, when using templates, the templated type is substituted upon template instantiation, meanings that anything you could write or perform with a “replace all” in the code, you can achieve with a template, for instance
type TMySum<T> = class FSum : T; procedure Add(value : T); end; procedure TMySum.Add(value : T); begin FSum := FSum + value; end;
can be used, and will work if T is a type that supports the ‘+’ operator (a String, a Float, an Integer, or just about anything upon which ‘+’ was overloaded). So you get a form of duck-typing, which is both flexible and powerful.
The downside is that if for T you pass a type that doesn’t support the ‘+’ operator, you’ll get an error message, and when
abusing making the most of the templates system, like C++ guys do, you can end up with fairly cryptic errors. Even nesting two templates can already lead to non-trivial errors.
Generics on the other hand are type-checked upon declaration, not upon instantiation, so if the code of a generic compiles, it’ll work. However, that requires specifying constraints, for instance in the form of interfaces the type you specialize upon should support.
The downside of generics is that even for basic stuff (such as addition) you need interfaces to constrain the type-checking, and code can get very convoluted as you end up having to implement a whole
jungle ecosystem of interfaces once you step outside of collections and containers.
You also have to be “creative” from time to time to bypass the limitations, for instance, the source-code for a generic-version of the above TMySum<T> would have to be as creative as what you find in the RTL’s Generics.Defaults for the comparisons (have a look there yourself).
So, what would it be for you?
For *scripting* purposes, would you prefer...
- Templates, expressiveness first, scripts can't get that complex anyway (42%, 40 Votes)
- Generics, strictness first, scripts are complex enough as they are (58%, 55 Votes)
Total Voters: 95