Type abstraction in C++

As shown in section generic (which discussed generic types), type abstraction in C++ may occur in various guises. One important means of type abstraction is to employ what we have called polymorphic base class hierarchies. For example, the function move, which was somewhat loosely characterized in slide 9-ex-quantification, may be defined in C++ as follows:
  Point* move(Point* p, int d); 
require int Point::x
Point* move(Point* p, int d) { p.x += d; return p; }

slide: example move

In effect, the function move accepts a pointer to an instance of Point, or any class derived from Point, satisfying the requirement that it has a public integer data member x. Similar restrictions generally hold when instantiating a template class, but in contrast to base class subtyping requirements, these restrictions will only be verified at link time.
  template< class T > 
requires T::value()
class P { public: P(T& r) : t(r) {} int operator==( P<T>& p) { return t.value() == p.t.value(); } private: T& t; };

slide: Type abstraction in C++

Consider the template class definition given in slide 9-cc-abs. Evidently, for the comparison function to operate properly, each instantiation type substituted for the type parameter T must satisfy the requirement that it has a public member function value.
  template< class T >
  class A { 
\fbox{ A }
public: virtual T value() = 0; }; class Int : public A {
\fbox{ Int <= A }
public: Int(int n = 0) : _n(n) {} int value() { return _n; } private: int _n; };

slide: Type instantiation

Such a requirement may also be expressed by defining an abstract class A defining a pure virtual member function value. See slide 9-cc-abs-2. The restrictions on instantiating P may then be stated informally as the requirement that each instantiation type T must be a subtype of A for arbitrary type X. The class Int is an example of a type complying with the implicit requirements imposed by the definition of P. An example of using P is given below
  Int i1, i2;
  P p1(i1), p2(i2);
  if ( p1 == p2 ) cout << "OK" << endl; 
OK

slide: Example P

Note, however, that the derivation of A is by no means necessary or in any way enforced by C++.