Ad Hoc Polymorphism

The ability for a class or function (or something else) to be parameterized based on a very limited (and usually explicitly enumerated) subset of types. Implemented via the following language techniques:

Overloading

If one defines the functions (in C++) using overloading

 bool is_positive (int t) { return t > 0; }
 bool is_positive (double t} { return t > 0; }

One can use these for those types above, or for any type which has an implicit conversion to one of these types above. So, the following will work:

 void foo (void)
 {
     int x = 5;
     float y = 4.2;
     double z = -8.23412;
     short q = -0x100;

if (is_positive(x)) cout << "x is positive\n"; if (is_positive(y)) cout << "y is positive\n"; if (is_positive(z)) cout << "z is positive\n"; if (is_positive(q)) cout << "q is positive\n"; }

It works for x and z because they are types the is_positive() function is defined on; it works for y and q because there are automatic conversions from short to int and from float to double in C++.

However, if you provide your own type, say big_int, things break:

 void foo2 (void)
 {
     big_int b = 5;
     if (is_positive(b)) cout << "b is positive\n";
 }

The compiler cannot find a suitable function (either is_positive(big_int) or is_positive (const big_int &), nor an automatic type conversion, so fails. If you define an appropriate type conversion (operator int or operator double), it might work. In either case, you need to do extra work to make is_positive() function with big_int.

A better solution is to use ParametricPolymorphism instead; to do that we use templates.

 template <class T> bool is_positive (const T& t) { return (t > 0); }

Now the is_positive function will work with any type that has > defined. (The downside is that is_positive may work in places where you don't expect it; such as passing in pointers. One reason why BoundedPolymorphism would be nice to have in CeePlusPlus).

Template Specialization

Type coercions


See OnUnderstandingTypes.


CategoryPolymorphism CategoryObjectOrientation CategoryCpp


EditText of this page (last edited May 16, 2010) or FindPage with title or text search