Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!bellcore!bytor From: bytor@ctt.bellcore.com (Ross Huitt) Newsgroups: comp.lang.c++ Subject: Re: Question about type conversion. Summary: use of cast operator Message-ID: <1991May2.163512.8587@bellcore.bellcore.com> Date: 2 May 91 16:35:12 GMT References: <9580001@hpdtczb.HP.COM> Sender: usenet@bellcore.bellcore.com (Poster of News) Organization: Computer Technology Transfer, Bellcore Lines: 55 In article <9580001@hpdtczb.HP.COM> dent@hpdtczb.HP.COM (Steve Dent) writes: //.... > One of the old C >routines returns a variable which may have multiple types: i.e an integer, >a double, or a pointer to a character. The user of this routine is >provide conversion macros to convert the variable to a known type. The >definition of the return structure is as follows: > >struct FIELD >{ > int type; > void *fieldValue; >} //.... >What I would like to do is create a C++ wrapper around this structure which >will take care of conversion for the user. So instead of: > var1 = convInt(ret1); >It would look like this: > var1 = ret1; >The real question is how do I inform the C++ compiler of type conversion rule >from a user defined class to a built in type? Is this possible? > >Steve Dent >Design Technology Center >Hewlett Packard How about something like: struct FIELD { int type; void *fieldValue; inline operator int(void) { return *(int*)fieldValue; } inline operator double(void) { return *(double*)fieldValue; } inline operator char *(void) { return (char *)fieldValue; } }; // this would let you do something like: FIELD f; int x = f; double y = f; char *s = f; However, I try to avoid cast operators for my classes unless I have a _very_ _very_ good reason for doing so. They can be very deadly because they may get invoked where you don't intend. This example looks harmless enough, though. :-) -bytor