How are Java generics different from C++ templates? Why can't I use int as a parameter?

后端 未结 8 1385
眼角桃花
眼角桃花 2020-12-12 19:02

I am trying to create

ArrayList myList = new ArrayList();

in Java but that does not work.

Can someone explain

8条回答
  •  我在风中等你
    2020-12-12 19:39

    They are very different concepts, which can be used to perform some, but not all of the same tasks. As said in the other responses, it would take a quite a bit to go over all the differences, but here's what I see as the broad strokes.

    Generics allow for runtime polymorphic containers through a single instantiation of a generic container. In Java, all the (non-primitive) objects are references, and all references are the same size (and have some of the same interface), and so can be handled by the bytecode. However, a necessary implication of having only instantiation of byte code is type eraser; you can't tell which class the container was instantiated with. This wouldn't work in c++ because of a fundamentally different object model, where objects aren't always references.

    Templates allow for compile time polymorphic containers through multiple instantiations (as well as template metaprogramming by providing a (currently weakly typed) language over the c++ type system.). This allows for specializations for given types, the downside being potential "code bloat" from needing more than one compiled instantiation.

    Templates are more powerful than generics; the former is effectively another language embedded within c++, while to the best of my knowledge, the latter is useful only in containers

提交回复
热议问题