template<typename T>
struct ordered
{
booloperator>(T const& rhs) const
{
// locate full derived object
T const& self = static_cast<T const&>(*this);
return rhs < self;
}
};
class Int : public ordered<Int>
{
public:
explicit Int(int value)
: value(value)
{
}
booloperator<(Int const& rhs) const
{
returnthis->value < rhs.value;
}
int value;
};
is the definition for Int recursive?? Int is expressed in terms of itself...
moreover by inheritance laws, Int IS-A kind of ordered<Int>, but then Int can be subsituted by its superclass so Int definition is recursive?
It is recursive in the same sense that the definition of (a node) of a linked list is recursive.
1 2 3 4 5
struct node
{
T value ;
node* next ; // node is an incomplete type at this point
};
In the same way, in the definition of the base class ordered<T> (parsed during phase one of the two phase compilation model) does not require that the type T must be a completely defined type.
Ok... is this code an error in view of the code on my last post?
1 2 3 4 5 6 7 8 9 10 11 12
class bogus : public ordered<Int>
{
public:
bogus(int val) : value(val) {}
private:
int value;
};
void useInt()
{
bool ok = bogus(2) > Int(5); // should crash but it does not!!
The reason I believe it should crash is the static_cast in:
1 2 3 4 5 6 7
template <typename T>
bool ordered<T>::operator>(T const& rhs) const
{
// locate full derived object
T const& self = static_cast<T const&>(*this); // this here! is it suspicious??
return rhs < self;
}
This was taken from a book and its author says it should crash, but it does not and I don't see why it should??
No checks are performed during runtime to guarantee that the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe.
you defined bogus as a kind of ordered<Int> class bogus : public ordered<Int>
so it can match this function ordered<Int>::operator>(Int const&) const