/* Template version of figure hierarchy */
#include <iostream>
#include <cstdlib>
#include <typeinfo>
using namespace std;
template <class T> class figure {
protected:
T x, y;
public:
figure(T i, T j) {
x = i;
y = j;
}
virtual T area() = 0;
};
template <class T> class triangle : public figure<T> {
public:
triangle(T i, T j) : figure<T>(i, j) {}
T area() {
return figure<T>::x * 0.5 * figure<T>::y;
}
};
template <class T> class rectangle : public figure<T> {
public:
rectangle(T i, T j) : figure<T>(i, j) {}
T area() {
return figure<T>::x * figure<T>::y;
}
};
template <class T> class circle : public figure<T> {
public:
circle(T i, T j = 0) : figure<T>(i, j) {}
T area() {
return 3.14 * figure<T>::x * figure<T>::x;
}
};
/* Fabric of objects of class figure */
figure<double> *generator() {
switch (rand() % 3) {
case 0: return new circle<double>(10.0);
case 1: return new triangle<double>(10.1, 5.3);
case 2: return new rectangle<double>(4.3, 5.7);
}
return 0;
}
int main() {
figure<double> *p; /* pointer to the base class */
int i;
int t = 0, r = 0, c = 0;
/* generating and counting objects */
for (i = 0; i < 10; i++) {
p = generator(); /* generating object */
cout << "Object has type " << typeid(*p).name();
cout << ". ";
/* keeping this object in mind */
if (typeid(*p) == typeid(triangle<double>)) t++;
if (typeid(*p) == typeid(rectangle<double>)) r++;
if (typeid(*p) == typeid(circle<double>)) c++;
/* Output square of the figure */
cout << "The square of the figure is" << p->area() << endl;
}
cout << endl;
cout << "There was generated next objects:\n";
cout << " triangles: " << t << endl;
cout << " rectangles: " << t << endl;
cout << " circles: " << c << endl;
return 0;
}
Правильно так якщо компілюєте на g++ або gcc. В gcc-3.4+ це вже виправлено. Попередні версії були більш суворі при наслідуванні від класів темплейтів.
А тепер пояснення:
The problem when compiling triangle is that its base class figure is unknown from the compiler, being a template class, so no way for the compiler to know any members from the base class.
