home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!ascent!eb
- From: eb@ascent.com (Ed Barton)
- Subject: Re: Conversion operators and typedef names
- In-reply-to: krc@wam.umd.edu's message of Tue, 21 Jul 1992 16:09:17 GMT
- Message-ID: <EB.92Jul27085934@ascent.ascent.com>
- Date: 27 Jul 92 08:59:34
- References: <1992Jul21.132931.8728@ohm.york.ac.uk> <1992Jul21.160917.27353@wam.umd.edu>
- Organization: Ascent Technology, Inc., Cambridge Massachusetts
- Lines: 49
-
-
- In article <1992Jul21.160917.27353@wam.umd.edu> krc@wam.umd.edu (Kevin R. Coombes) writes:
-
- class MyTime {
- ...
- operator time_t(void); // Does this make you queasy?
- ...
- };
-
- Technically, this works. However, when I have tried it, I have found
- that it is usually a bad idea in practice. Remember that a typedef
- does not define a new type, so on a particular machine, this is just
- as if you had defined operator unsigned long() or operator long() or
- whatever, depending on how time_t is actually defined. That means you
- can't have an operator time_t() and an operator other_t() at the same
- time, if other_t is a typedef name that happens to come out the same
- as time_t on your machine. Also, the compiler will insert a call to
- operator time_t() if you call a function f(unsigned long) on one of
- your MyTime objects. time_t is just the same as unsigned long (or
- whatever) for purposes of overloading, so you will get a conversion
- even when the unsigned long that is expected is not really a time_t.
-
- (In my case, I had two different time representations that were both
- internally represented as the same basic type.)
-
- The alternative, assuming you really do want to be able to convert your
- time objects into time_t's, is to supply a method like
-
- time_t MyTime::getValue(void);
-
- At least when typedefs are involved, this is a better idea. For
- operator struct tm(), the answer might be different, if you can figure
- out whether it should do a GMT or local time conversion.
-
- The implicit conversions provided by constructors lead to similar
- problems, if you have one-argument constructors that take time_t or
- similar arguments. Depending on the actual typedefs on your machine,
- you might be surprised to have a plain integer in the code converted
- into a MyTime when there is a constructor taking a time_t.
-
- Any kind of overloading on typedef names can lead to portability
- problems, if the typedef names are likely to be defined differently on
- different machines. For instance, if you have both operator int() and
- operator time_t(), and time_t happens to be defined as int on some
- machines, then you will have a clash on those machines but not others.
-
-
-
-
-