Many programmers believe that C ++ templates and generic drugs (such as Java) - this is the same thing, because the syntax is similar: in both cases, you can write something like
Java Generics are associated with the idea of "erasure types» (type erasure). This technique eliminates the type parameters when the source code is converted to bytecode JVM.
List <T>. To find the differences, let's see what templates and generics, and how they are implemented in each of the languages.Java Generics are associated with the idea of "erasure types» (type erasure). This technique eliminates the type parameters when the source code is converted to bytecode JVM.
Suppose that you have a Java-code:
At compile time, it will be converted:
Using generalizations Java does not impact on our ability, but to make the code more beautiful. Therefore, generics in Java are often called "syntactic sugar".
Generics are very different from the patterns C ++. Patterns in C ++ is a set of macros, create a new copy of the boilerplate code for each type. This is particularly evident in the following example: an instance of
MyClass <Foo> not be able, together with MyClass <Bar> to use a static variable. A two copies of MyClass <Foo> will share the static variable.
To illustrate this example, consider the following code:
In Java, the various instances of
MyClass can share static variables, regardless of the type parameters.
Because of differences in the architecture of generic Java and C ++ templates have many differences:
- C ++ templates can use primitive types, such as,
int, a generic Java - no, they have to useInteger. - Java allows to specify restrictions on the type passed as a parameter. For example, you can use generics to implement
CardDeckand indicate that the type parameter must inherit from CardGame. - In C ++, you can create an instance of a type, pass parameters, and Java - no.
- Java does not allow classes, pass parameters (eg,
FooinMyClass<Foo>) for static methods and variables, as they can be shared inMyClass <Foo>andMyClass<Bar>. In C ++ - classes are different, so the type of the parameter can be used for static methods and variables. - In all instances of Java
MyClass<T>, regardless of their parameters are the same type.Parameters types are destroyed after compilation. In C ++, instances with different parameter types - different types.
Remember that although generic Java and C ++ templates look similar, they are different things.
Комментариев нет:
Отправить комментарий