Re: stroustrup, void*, and reinterpret_cast
Frederick Gotham wrote:
I don't have Bjarne's book here with me, so I can't look over the code
snippet. Perhaps he used reinterpret_cast simply because it slipped his
mind
that static_cast would get the job done.
It can get pretty complex for me, namely I also want to store 2 types
of pointers in a virtual hierarchy as void* and then retrieve it and
narrow it to the base class pointer. The question in the following
hierarchy of widening to an interface from 2 different derivations, and
then further widening to void*, and then being able to narrow back from
void* to the interface, what's better than my use of
reinterpret_cast<>.
class Arc;
struct ArcLink {
virtual Arc* ThisArc () = 0;
virtual ArcLink* NextLink () = 0;
};
class Arc : public ArcLink {
... some data members
public:
virtual Arc* ThisArc () { return this; }
virtual ArcLink* NextLink() { return 0; }
... additional functionality
};
class ArcLinkImpl : public ArcLink {
Arc* arc;
ArcLink* tail;
public:
virtual Arc* ThisArc () { return arc; }
virtual ArcLink* NextLink () { return tail; }
};
// from utilities for a red-black set
struct IntSetElem {
void* obj;
private:
IntSetElem* left;
IntSetElem* right;
int key;
bool color;
};
// and the question is, what casts to and from elem->obj
main () {
IntSetElem* elem1 = ...; // get an element from a set
IntSetElem* elem2 = ...; // get another
Arc* arc = ...; // create an arc
ArcLinkImpl* arclink = ...; // create an arclink
ArcLink* intf = arc; // widen
elem1->obj = reinterpret_cast<void*>(intf);
//??? can I pass arc directly to the cast here
intf = arclink; // a different widen
elem2->obj = reinterpret_cast<void*>(intf);
//??? can I pass arclink directly to the cast here
// now fetch Arc* as ArcLink*
intf = reinterpret_cast<ArcLink*>(elem1->obj);
// I bet this is ok because I made sure to stuff it
// as an ArcLink* interface pointer
// what's better???
// now fetch ArcLinkImpl* as ArcLink*
intf = reinterpret_cast<ArcLink*>(elem2->obj);
// again ok because I stuffed the ArcLinkImpl*
// as an ArcLink*
// what's better???
}
Andy
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]