Lecture 5 - Slide 31 : 40
Templates versus generics in Java, C# and C++
Templates in C++ can be compared with generics in Java and C#
Java
Type erasure: type parameters are compiled away.
Problems with reflection - cannot reestablish actual type parameters
C#
Reflection with generic types is possible
Support of constraints on formal parameter types:
where clauses
where class
;
where struct
;
where new()
;
where C
;
where C, I
When value types are used as actual type parameters
Separate instantiations are generated
C++
Template specialization, and partial specialization
Allow alternative implementation for certain template parameters
To avoid
code bloat
in some situations
Containers of pointers share their implementation (§25.3,
4ed
)
Powerful compile time calculations (metaprogramming) - Turing complete
Templates cannot be compiled as such (§23.3.2,
4ed
)
The instantiations are compiled
Only relatively superficial compiler check of the template - before any instantiation
Relies on
compile-time duck typing