Search code examples
javac++genericstemplates

What is the Java equivalent of C++'s templates?


What is the Java equivalent of C++'s templates?

I know that there is an interface called Template. Is that related?


Solution

  • Templates as in C++ do not exist in Java. The best approximation is generics.

    One huge difference is that in C++ this is legal:

    <typename T> T sum(T a, T b) { return a + b; } 
    

    There is no equivalent construct in Java. The best that you can say is

    <T extends Something> T Sum(T a, T b) { return a.add(b); }
    

    where Something has a method called add.

    In C++, what happens is that the compiler creates a compiled version of the template for all instances of the template used in code. Thus if we have

    int intResult = sum(5, 4);
    double doubleResult = sum(5.0, 4.0);
    

    then the C++ compiler will compile a version of sum for int and a version of sum for double.

    In Java, there is the concept of erasure. What happens is that the compiler removes all references to the generic type parameters. The compiler creates only one compiled version of the code regardless of how many times it is used with different type parameters.

    Other differences