Generic Programming in C++ and Java
Total Page:16
File Type:pdf, Size:1020Kb
60 IJCSNS International Journal of Computer Science and Network Security, VOL.11 No.9, September 2011 Generic Programming in C++ and Java Shilpa Mathur Bhagwant University, India ABSTRACT characterizations of the domain for which each This paper is about Generic Programming in Java and C++. One algorithm is the most efficient. of the main motivations for including generic programming support in both Java and C++ is to provide type-safe homogeneous containers. To improve the support for generic programming in C++, we introduce concepts to express the 2. GENERIC PROGRAMMING syntactic and semantic behavior of types and to constrain the type parameters in a C++ template. Generic programming is implemented differently in KEYWORDS different programming languages. Generic programming Generic programming, Constrained Generics, Parametric is a kind of polymorphism. Each variable and routine Polymorphism, C++ templates, C++ concepts, Standard which can have different types depending on certain Template Library (STL). circumstances during the execution of a program is polymorphic.Genericity is also called parametric polymorphism. 1. TERMINOLOGY 2.1. JAVA Generic programming can be seen simply as the act of using type parameters. A broader definition was given by Java is an object oriented language that allows the organizers of a seminar on generic programming: programmers to create generic classes. When creating Generic programming is a sub-discipline of computer generic classes the developer puts at least one type science that deals with finding abstract representation of parameter in angle brackets after each class or interface efficient algorithms, data structures and other software declaration. These type parameters may be bound or concepts and with their systematic organization. The goal unbound in java. of generic programming is to express algorithms and data structures in a broadly adaptable, interoperable form that 2.1.1 Genericity internals allows their direct use in software construction. Key ideas include: The compilation of a generic class in Java is homogeneous • Expressing algorithms with minimal assumptions for each instantiation of generic type. The complier about data abstractions, and vice versa, thus removes all type information related to type parameters. making them as interoperable as possible. This process is called type erasure. By erasing the type parameters, raw types are created. This is done by Java • Lifting of a concrete algorithm to as general a compiler in order to be backward compatible with older level as possible without losing efficiency; i.e., non-generic libraries. The raw type of Foo<Integer> is the most abstract form such that when Foo. Furthermore, it is impossible to use the type specialized back to the concrete case the result parameter at run-time. It is removed by the compiler. An is just as efficient as the original algorithm. attempt to compile the following class results in an error: • When the result of lifting is not general enough to public class FooBar<T> cover all uses of an algorithm, additionally { providing a more general form, but ensuring public static void main(String args[]) that the most efficient specialized form is {T t = new T(); //not allowed } automatically chosen when applicable. } • Providing more than one generic algorithm for the same purpose and at the same level of 2.1.2 Wildcards abstraction, when none dominates the others in In Java the type of generic container can be unknown. efficiency for all inputs. This introduces the Instead of a type that replaces the type parameter the necessity to provide sufficiently precise wildcard ? is used. We can use this wildcard bound or Manuscript received September 5, 2011 Manuscript revised September 20, 2011 IJCSNS International Journal of Computer Science and Network Security, VOL.11 No.9, September 2011 61 unbound. When using a wildcard for a generic container subtypes can be replaced for the type variable. Consider we must be aware of the fact that some constraints exist the example: on variables which represent such containers. This code snippet shows the usage of a wildcard: Interface UploadAble { String getPath() ; } Public static void showAll(List ? extends Printable> elems){ Class ToUpload<Payload extends UploadAble>{ for (Printable p : elems) System.out.Println(p); } private List<Payload>elems; public void uploadAll() { This static method showAll() can be called only with list for(Payload p : elems) { which contain subtypes of Printable. Our Printable a.Uploader.upload( p.getPath()); interface declares a toString method. Therefore for each } element in this list we can output it to standard out. The } complier can statically ensure that each element provides a // ‘add’ also implement here toString method, because each element implements the Printable interface. If an object in java provides the This generic ToUpload class has only one type parameter. toString method, then we can output its string retranslation We can use this generic class as a container for objects to standard out. If you are familiar with Java you will which are uploadable.An object is uploadable if it know that we don’t need a Printable interface which implements the UploadAble interface and provides the declares the toString. Everything (except primitive types) getpath method. For type parameter Payload only is a subtype of Object and Object already implements the subtypes of UplaodAble can be inserted. Subtypes of toString method. Our example is used to demonstrate UploadAble must implement the getPath method which is wildcards. Our declaration type of our elems variable can called within uploadAll.With this approach the library be List<? Extends Object> and this declaration is user is constrained in such a way that the compiler ensures equivalent to List<?>. that the type inserted for Payload must implement the Furthermore we must be aware of the fact that within getPath method. showAll we can’t perform any writing operation which In Java it is also possible that the library developer uses would insert objects into our elems list. If extends is used type parameters recursively. This is necessary when our container is accessible read only. binary methods are implemented by classes which We can also use super keyword. This allows only super implement generic interfaces. Consider the code snipped types of a bound to replace the type parameter. In this given in Figure 1. example the bound is Item. For example: The class Integer is a simplified form of Java’s standard class with the same name.Integer is extended from the public static void initList ( List < ? super Item> items) { generic Comparable<A> interface. This may be confusing, // in the loop generate some ‘Items’ and insert them into but it is well defined. This type of genericity is based on //items the formal model of F-bounded Polymorphism for OO items.add(. .); programming. } The advantage of this approach is that the type of formal Into the items we can add anything of type Item or its parameter is defined by the type parameter not by super type.in this case we can’t read from items. The list subtyping. This avoids constraints on subtyping items is only writable. (covariance and binary methods) and it ensures that this and that have the same declared type. 2.1.3 Library Development Figure1 In Java the type variable can be used without a bound. interface Comparable<A> { Often it is not required to constrain the library user. Boolean equal<T that> Consider any unconstrained generic container from the } JDK .In this case it is even desirable that a user can create a collection of any type. When no constraint is specified, Class Integer implements Comparable<Integer> { the Java compiler uses implicitly Object as a constraint. private int value; Each reference type (except the primitive types: boolean equal (Integer that) { int,double,..)in Java is a subtype of Object. return this.value == that.intValue(); } If the library developer wants to constrain a generic type, } he/she uses the keyword extends. Extends state that only 62 IJCSNS International Journal of Computer Science and Network Security, VOL.11 No.9, September 2011 2.1.4 Library Usage template to C++ concepts is supposed to eliminate all these disadvantages. In this section a generic find function The library user can use the provided ToUpload class in will be extended with C++ concepts. This example will some application: give an introduction on how C++ concepts are used and what they offer. ToUpload files = new ToUpload<Myfile> () ; C++ concepts will provide three different means to //generate some files- f1 and f2 constrain generic types. Here is a short description of their files.add(f1); purposes: files.add(f2); files.uploadAll(); concept: This is an abstract interface-like collection of functions, operators and associated types. If a type is The reuse of the ToUpload container is quite intuitive. If supposed to meet the requirements of a particular concept the library use uses its own class for the type parameter it must provide all the functions and operators ad specified Payload which does not implement getPath, then the in the concepts. An associated type for functions and compilation of this little code snippet will fail. The error operators within the concept in order to determine their message of the compiler will tell the user that his/her class types. does not implement the UploadAble interface. The getPath method is not provided by the user defined class. where: Where clauses constrain the type parameter in Recursive type parameters can also be used by the library terms of a particular concepts. A concrete type must meet user, for example a list is supposed to be ordered is that concepts in order to be correct substitution for a type declared like this: parameter. An experimental version of g++ which supports concepts uses requires clauses instead of where OrderedList<T extends Orderable<T>> clauses. Even the library user can constrain himself in order to concept_map: It specifies how a type meets the avoid bugs.