60 IJCSNS International Journal of Computer Science and Network Security, VOL.11 No.9, September 2011

Generic Programming in ++ and

Shilpa Mathur

Bhagwant University, India

ABSTRACT characterizations of the domain for which each This paper is about Generic Programming in Java and C++. One 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++ . Generic programming is implemented differently in KEYWORDS different programming languages. Generic programming Generic programming, Constrained Generics, Parametric is a of polymorphism. Each variable and routine Polymorphism, C++ templates, C++ concepts, Standard which can have different types depending on certain Template (STL). circumstances during the execution of a program is polymorphic.Genericity is also called . 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 efficient , 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 . By erasing the type parameters, raw types are created. This is done by Java • Lifting of a concrete algorithm to as general a in order to be backward compatible with older level as possible without losing efficiency; i.e., non-generic libraries. The raw type of Foo 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 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{ for (Printable p : elems) System.out.Println(p); } private Listelems; 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 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 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 . 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 { Often it is not required to constrain the library user. Boolean equal 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 { 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 () ; 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> clauses.

Even the library user can constrain himself in order to concept_map: It specifies how a type meets the avoid bugs. In this case only subtypes of Orderable requirements of a concept. It maps the type into the can be used to create an OrderedList.This is ensured by domain of this particular concept. A concept_map can be the complier. An OrderedList can contain only elements template too. which are subtypes of Orderable and a partial ordering exists on this collection. We use recursive bounds to avoid 2.2.3 Library development problems with covariance. Consider a fragile STL find function using templates. 2.2. C++ template InputIterator 2.2.1 Genericity internals find(InputIterator first,InputIterator last,const T& value) { while(first v; compiling heterogeneously the compiler can optimize the find (v.begin(), v.end(), 5); //okay code much better especially for primitive types. std : : List l; find(l.begin(), l.end(), 41); // error 2.2.2 C++ Concepts Both vector and list are InputIterators.The reason Current C++ templates system is fragile. It does not why finds fails to complie with list iterators is because provide any for constrained type parameters. they do not provide a < operator. The less-than-operator is It can’t check whether concrete types meet requirements part of the termination condition of the while loop within when instantiated with type parameters. Library the implementation of this find algorithm. When development and usage suffer because these contexts are compiling this code we get an error message saying that in not divides. Any time a user inserts a type which does not the implementation of this find algorithm we don’t have a meet all the requirements as expected by the generic type, less-than-operator. and then error messages combine the context of library development with that of usage. An upgrade of C++

IJCSNS International Journal of Computer Science and Network Security, VOL.11 No.9, September 2011 63

In this section we will show how C++ concepts are used to equivalent to STL’s find, this is because of backward create “better” generic functions. First we must create an compatibility of templates and concepts).It says” The type InputIterator concept. The first and second arguments of of the type parameter Iter must meet the requirement of find are supposed to meet the requirements of the the InputIterator concept and the type of dereferencing InputIterator concept. When creating this concept, all operator InputIterator: value_type must be equal- functions and operators an InputIterator must provide are comparable with the type of the type parameter T”.T is the part of this concept, those are the increment (++) and the type we are looking for. dereferencing (*) operator. The dereferencing operator In terms of C++ concepts we are not yet finished. We returns an instance of a type which is determined by the must establish a mapping between concrete types and the itself. When dereferencing an iterator (iterators are InputIterator concept. This is done because otherwise the pointers) which points to list it returns an instance of compiler does not know which types meet this a different type than an iterator which points to an element InputIterator concept.To establish a mapping between int* of a different type. That’s what the associated types are and the InputIterator concept we can declare this concept used for, in our case the associated type value_type is map: changed depending on the type of iterator. The associated type difference_type determines the distance between the concept_map InputIterator { . . . }; begin and end of the iterator. This type is also iterator dependent. When iterating over an array of integers this But this is not satisfactory because every pointer meets the distance is an int.This type varies as the iterator which is requirements of an used. All we know so far is that the difference_type has to InputIterator concept. Therefore a concept_map can be meet the requirement of a SignedIntegral type. This nested template: where clause states how this associated type difference_type has to behave. It must be an integer like template type can be positive and negative. This is a complete concept_map InputIterator{ InputIterator concept which states all requirements on typedef T value_type; types: typedef ptrdiff_t difference_type; }; concept InputIterator { The body of a concept_map states how a type meets the typename value_type; requirements of a concept. In this case associated types typename difference_type; value_type and difference_type are given concrete types where SignedIntegral; which are determined by the type variable T. Iter& operator++(Iter&); Iter operator++(Iter&,int); 2.2.4 Library usage bool operator= =(Iter,Iter); value_type operator*(Iter); The library is now ready for usage, the library user uses }; the new find function:

Futhermore, we need an EqualityComparable concept int main() { which ensures that types are comparable using equal. In List persons; terms C++ they must overload the = = operator. It also persons.push_back(p1); /*p1-p3 are instances of ensures that they have the same type. Person*/ persons.push.back(p2); This is our extended find version: persons.push_back(p3); find(persons.begin(),persons.end(),person_looking_for); template } where InputIterator && EqualityComparable: : The compiler ensures that the user uses only types which value_type,T> meet all the requirements of find. Iter find (Iter first,Iter last,const T& value) { while(first !=last && !(*first = = value) ) ++first; 3. CONCLUSION return first; } This paper presents how generic programming is The most interesting line from the point of C++ concepts implemented in Java and C++.Java is a language where is the where clause (if removes, the implementation is the current system for generic programming distinguishes between context of library development and the context

64 IJCSNS International Journal of Computer Science and Network Security, VOL.11 No.9, September 2011

of library usage. The compiler diagnoses the error .In the correct context if some bug appeared somewhere in one of these contexts. Java is efficient and user friendly when developing and using generic libraries.C++ templates are fragile. An upgrade from templates to C++ concepts is supposed to eliminate these fragilities. Although this upgrade is not part of C++ standard yet, the expectations are quite promising.

REFERENCES [1] A.Andrei. Modern C++ Design: Generic Programming and Applied. Addison- Wesley Professional 2001 [2] R.Garcia, J.Jarvi, A.Lumsdaine, J.G.Siek and J.Willcock.A comparative study of language Support for generic programming [3] B.Stroustrup.The C++ . Addison- Wesley Longman Publishing Co., Inc., Boston, MA, USA, 2000. [4] .Parameterized types for C++.Journal of Object-Oriented Programming, 1(5):5-16, 1989 [5] Joseph A.Bank, Barbara Liskov and Andrew C.Myers.Parameterized Types and Java. Technical report MIT LCS TM-553 [6] Luca Cardelli and Peter Wegner.On understanding types, data abstraction and polymorphism. [7] Brian Cabana, Suad Alagic and Jeff Faulkner. Parametric polymorphism for Java: is there any Hope in sight? SIGPLAN Not.,39(12):22-31,2004. [8] David vandevoorde and Nicoli M.Josuttis.C++ Templates: The Complete Guide. [9] Sun microsystems inc.-a tutorial to generics. http://java.sun.com/docs/books/tutorial/generics/index.html. [10] Concepts: Linguistic Support for Generic Programming in C++.Douglas Gregor, Jaakko J¨arvi, Jeremy Siek. [11] A Comparative Study of Language Support for Generic Programming. Ronald Garcia Jaakko J¨arvi Andrew Lumsdaine, Jeremy Siek Jeremiah Willcock. [12] M.Abadi and L.Cardelli. On subtyping and matching.

Shilpa Mathur has done Bachelors of Engineering in Information Technology from Rajasthan University, India in the year 2005.She has experience of working as a Lecturer in an Engineering College. Currently she is pursuing Masters of Technology in Software Engineering from Bhagwant University, India.