3 ms·
Some people that are complaining about C++ templates (and suggesting generics from other languages as alternatives) are missing the code generation aspect of te
by Barraketh 8y ago
Some people that are complaining about C++ templates (and suggesting generics from other languages as alternatives) are missing the code generation aspect of templates.
Generics operate entirely at the Type level. For instance (using java)
List<Integer> list = new ArrayList<Integer>();
list.add(1);
Integer i = list.get(0);
is under the hood equivalent to
List<Object> list = new ArrayList<Object>();
list.add(new Integer(1));
Integer i = (Integer)list.get(0);
The differences between the two snippets are entirely at the type level - they compile to the exact same bytecode. Templates are strictly more powerful - they allow you to generate different code for each instantiation. The most obvious place where this is useful is when dealing with primitives that take up different sizes in memory. This is why you can't use generics in Java with primitives - you need Objects, because pointers to objects are always the same size. But if you want performance, so you want to be able to represent collections of primitives generically, then you need the power of templates because you need your code to compile to different things depending on the template parameters.
- aphexairlines 8y agoGenerics don't have to be implemented with type erasure at the bytecode level. The CLR doesn't, for example. http://www.jprl.com/Blog/archive/development/2007/Aug-31.html#jcs-cs-implementation http://www.jprl.com/Blog/archive/development/2007/Aug-31.htm...