TITLE: Question on constrained genericity PROBLEM: beauge@loria.fr (Lionel Beauge'), 11 Oct 94 Can we use constrained genericity in C++ ? [ There is a detailed discussion of constrained genericity in "Object Oriented Software Construction" by Bertrand Meyer. -adc ] Imagine this inheritance graph : A parent / \ | A1 A2 heir / \ / \ A11 A12 A21 A22 \ / A23 ../.. Now, we want to define a template class B : Class B is a template class which is declared with formal generic parameter that conforms to certain type of class. (A1 conforms to another, A, if class A1 is a descendant of A.) for example : ------------- template class B ... { ... A2* a; ... a->f(..); /* f is a virtual public fonction of class A2 */ ... } we can define : ------------- B b; ok ! B b; ok ! B b; ok; B b; Error : A1 doesn't conform to A2 ! RESPONSE: clamage@Eng.Sun.COM (Steve Clamage), 12 Oct 94 There is no direct language mechanism to express such constraints, but you can express them indirectly. Example: template class B { /* inline */ void constraint(T* t) { A* a = t; } ... }; Function 'constraint' will not compile unless there is an implicit conversion from T* to A*; this is true if T is publicly derived from A. Some compilers validate inline template functions whether they are used or not; in that case, this is all you need. Others validate the functions only if called, so you would then have to call 'constraint' from the template constructors of B. (It would probably be sufficient to call it from the destructor of B, but protection is then less certain.) The reasons why there is no direct language mechanism (although it has been proposed several times) to express constrained genericity are explained in detail in Stroustrup's "Design and Evolution of C++", in section 15.4.