In Java, static variables are shared across instances of MyClass, regardless of the different type parameters. Java generics and C++ templates have a number of other differences. These include:

  • C++ templates can use primitive types, like int. Java cannot and must instead use Integer.
  • In Java,you can restrict the template's type parameters to be of a certain type. For instance,you might use generics to implement a CardDeck and specify that the type parameter must extend from CardGame.
  • In C++, the type parameter can be instantiated, whereas Java does not support this.
  • In Java, the type parameter (i.e., the Foo in MyClass) cannot be used for static methods and variables, since these would be shared between MyClass and MyClass. In C++, these classes are different, so the type parameter can be used for static methods and variables.
  • In Java, all instances of MyClass, regardless of their type parameters, are the same type. The type parameters are erased at runtime. In C++, instances with different type parameters are different types. Remember: Although Java generics and C++ templates look the same in many ways, they are very different.

results matching ""

    No results matching ""