Bounded Polymorphism

BoundedPolymorphism is ParametricPolymorphism where a restriction on the set of types a class/function is polymorphic over can be specified; it is an error to try and use a polymorphic function/class with a type which it doesn't support.

JavaGenerics support BoundedPolymorphism via JavaInterfaces?; the definition of a generic in Java can specify an interface or class that the class parameter must implement/extend. If no class or interface is specified, "extends Object" is assumed. Only operations which are supported by the declared type are allowed in the body of a generic (at least not without a typecast; one can downcast a generic parameter in Java just like any other object reference).

Attempting to instantiate a generic on a type not supported is immediately flagged by the compiler.

Oh, and generics won't work on intrinsic types (int, float, char, double, etc.). However, the new BoxingConversions feature in JDK 1.5 might make you forget about that little problem...

EiffelLanguage generics are very similar.

CeePlusPlus, on the other hand, does not support bounded polymorphism (at least not directly); it uses LatentTyping. When a template is instantiated, little error-checking is done to see if the type provided is consistent with the template's definition. For example, one can write the following generic functor object in C++:

 template <class T> class OneAdder? {
      T operator () (const T& t) {return t + 1;}

Not very useful, but good enough for pedagogical purposes. If you try and instantiate this object on a type that doesn't support addition (such as an abritrary structure), the compiler won't complain.... yet.

 struct Foo { int x; int y; };
 OneAdder?<struct Foo> fooAdder; // not an error

Only when you try and use an unsupported function, do you get an error.

 struct Foo foo;
 foo.x = 1; foo.y = 2;

struct Foo fooPlusOne = fooAdder(foo); // ERROR; struct Foo does not have operator+

Unfortunately, the error message you do get may be rather bizarre and incomprehensible.

Some consider the C++ approach superior (Many C++ libraries use the laziness of the generic-checking to full advantage), others think it smells. See LatentTypesSmell for more on this.

C++ generics have the advantage of working on any C++ type; non-objects aren't second class in C++. Whether or not this is a good thing is a longstanding HolyWar.


View edit of August 31, 2006 or FindPage with title or text search