Original version; naive translation of the
model into C++.
class U
{
public:
virtual void cv (T * t);
virtual void ctv (B * b);
};
#endif
// u.cpp
#include <stream.h>
#include "u.h"
void U :: cv (T * t)
{
cout << "U\n";
}
void U :: ctv (B * b)
{
cout << "U\n";
}
class T
{
};
#endif
class M : public T
{
};
#endif
class B : public M
{
};
#endif
class D : public U
{
public:
virtual void ctv (M * m); /* covariance
*/
virtual void cv (M * b); /* contravariance
*/
virtual void cv (T * t); /* added
to match the new semantics */
virtual void ctv (B * b); /* added
to match the new semantics */
};
#endif
#include <stream.h>
#include <typeinfo>
#include "d.h"
void D :: ctv (M * m) /* covariance */
{
cout << "D ";
}
void D :: cv (M * m) /* contravariance */
{
cout << "D ";
}
/*
* added code to simulate the covariant behavior in column 3 and
slot(1,2)
* "correct" the yellow differences of the C++
Table lines 1 and 2
* "correct" the blue difference slot (1,2)
*/
void D :: cv (T * t) /* added to match the new semantics : slot(1,2)
and slot (2,3), and (3,3)*/
{
TOP * ttt = new T(); /*to test ignoring
the internal coding of class names */
if (strcmp(typeid(*t).name(),typeid(* ttt).name())==0)
{
U::cv(t); // now accepts slot(1,2)
} else {
V::cv((M *) t); //look for
the most specialized in slot (2,3) and (3,3)
}
}
/*
* added code to simulate the covariant behavior in column 3 and
slot(1,2)
* "correct" the yellow difference of the C++
Table line 6.
*/
void D :: ctv(B * b) /* added to match the new semantics :
force the choice slot(6,3)*/
{
ctv ((M *) b);
}
main () {
U *u = new U();
U *w = new D();
D *d = new D();
T t;
M m;
B b;
cout << "--Serie 1\n";
u->cv(&t);
u->cv(&m);
u->cv(&b);
//u->ctv(&t);
cout << " type `B'
is not a base type for type `T'\n";
//u->ctv(&m);
cout << " type `B'
is not a base type for type `M'\n";
u->ctv(&b);
cout << "--Serie 2\n";
d->cv(&t); //accepted!
// cout << " type `M' is not a
base type for type `T'\n";
d->cv(&m);
d->cv(&b);
//d->ctv(&t);
cout << " type `M'
is not a base type for type `T'\n";
d->ctv(&m);
d->ctv(&b);
cout << "--Serie 3\n";
w->cv(&t);
w->cv(&m);
w->cv(&b);
//w->ctv(&t);
cout << " type `B'
is not a base type for type `T'\n";
//w->ctv(&m);
cout << " type `B'
is not a base type for type `M'\n";
w->ctv(&b);
};