10-08-2009, 09:09
|
|
|
חבר מתאריך: 09.08.09
הודעות: 2
|
|
זה לא templates
templates זה המנגנון ב-CPP שממש משכפל קוד ב-compile-time עבור כל טיפוס שעושים עבורו instantiation. ב-JAVA יש מנגנון generics שמגן עליך ב-compile-time מהעברת טיפוסים לא נכונים וחוסך cast-ים, אבל היכולת היא ממש להשתמש באותו קוד עבור טיפוסים שונים וזה משהו שמתרחש ב-run-time.
גם התיעוד של SUN מבדיל בין המונחים:
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.
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.
עוד הבדל הוא שבעוד שב-CPP בתוך ה-template יש לך את כל המידע על טיפוס (וזוהי דרישה בעצם - אי-אפשר לבצע instantiation ל-incomplete type) בג'אווה קורה בדיוק ההפך: מבצעים את מה שנקרא במונחי ג'אווה type erasure ומעלימים את כל המידע על הטיפוס ה"טמפלייטי".
בג'אווה יש גם מושג של templates אבל הוא מדבר על משהו אחר לגמרי:
http://java.sun.com/javase/6/docs/a.../Templates.html
|