Tuesday, March 20, 2007

Java Generics vs. C++ Templates

While generics look like the C++ templates, it is important to note that they are not the same.

Generics simply provide compile-time type safety and eliminate the need for casts. The main difference is encapsulation: errors are flagged where they occur and not later at some use site, and source code is not exposed to clients. Generics use a technique known as type erasure as described above, and the compiler keeps track of the generics internally, and all instances use the same class file at compile/run time.

Java Generic -- Type Erasure;Java Generic的目的是编译期类型检查。
编译结果里面不保留具体 generic type信息,运行期不进行generic type检查,也无法用Reflection获取generic type信息。支持wildcard.Java 的generic type信息只能够存在于Class定义中,而不是instance中。所以,java只能支持Field, Method的generic type信息,这些信息存放在class文件的contant pool中,作为字符串常量出现,标志是signature.Field, Method的Reflection API可以获取Class定义中声明的generic type.

package poly;
import java.util.Collection;

public class Master {
private T t ;
public T showGeneric(Collection t){
//return new T(); --error
但对于method内部的局部变量是不能实现的。
return this.t;
}
}

A C++ template on the other hand is just a fancy macro processor; whenever a template class is instantiated with a new class, the entire code for the class is reproduced and recompiled for the new class.

[相似于C++]C# Generic -- Reification
C# Generic的编译结果保留了generic type信息,从而可以运行时generic type检查,Reflection可以获取instance的generic type信息。不支持wildcard。generic type信息存放在每个Instance中。