I've often thought of C++'s templates (when used in the "straightforward" manner, anyway) as more of compile-time duck typing than a real generic type system. Even moving from C++ to Java took a while to get used to.
template <class T>
T* allocate() {
return new T();
}
That's not possible in Java because of type erasure. When you try something like that, you get an error message like: Erasure.java:12: error: unexpected type
return new T();
^
required: class
found: type parameter T
where T is a type-variable:
T extends Object declared in class Foo
Again, this is because of type erasure: Foo<T> is really Foo<Object>, where Java just does a cast for you to T in all of the right places. It does not actually know the type. For me, that lead to all sort of contortions because a class Foo<T> could not allocate objects of type T internally. I needed to create factory methods in other places which Foo would call. In the instance I'm thinking of, those factory methods ended up living in derived classes.C++ templates have its issues, but it allows parametric polymorphism. In Java, I could not write such code, which was what I was used to. Because of type erasure, I was forced more towards subtype polymorphism, even though I was implementing generic classes.
The typical workaround in Java is to either pass around .class instances, or to do tricks with anonymous subclasses to create a type token. [2]
[1]: https://ideone.com/th18eh [2]: http://docs.guava-libraries.googlecode.com/git/javadoc/com/g...
Oh yes, I'm not saying it's possible to do this in Java, AFAIK you're right that it's not, I'm saying I'm not sure it's because of type erasure, at least type erasure on its own.