typedef int: adding operators? (opAdd, etc.)

Daniel Keep daniel.keep.lists at gmail.com
Tue Apr 3 23:04:22 PDT 2007



BCS wrote:
> Reply to Charles,
> 
>> Is there any way to add operators defined on a type which is defined
>> off of the built-in types?
>>
>> In particular, it would be nice, e.g., to be able to define types for
>> byteNo, wordNo, etc., and be able to add them together (where, say,
>> one word == 4 bytes).
>>
>> Currently I'm doing this kind of thing on an ad hoc basis, but that
>> means that type information is spread out all over the place, and it
>> would be nice to concentrate it in one place. (In one instance I'm
>> converting between record ID's and disk addresses.  It's easy enough
>> to do, but if I change the record size I'll need to track down each
>> place where I cast from one type to another.  Not optimal.)
>>
>> I suppose I could just write a special function for each conversion,
>> and stick them all in the same place, and I may do just that, but this
>> approach strikes me as less than ideal.
>>
>> I suppose defining:
>> ByteNo opAdd(ByteNo b, WordNo w) { ... }
>> and then calling it via:
>> ByteNo b1 = opAdd(b0, w0);
>> isn't horrendous, but it's not as nice as
>> ByteNo b1 = b0 + w0;
> 
> somewhere there is a compile time units lib that does much of this kind
> of thing. It wraps the internal real type in a struct and forces the
> conventions to get to it. It might not be quite what you want because it
> would convert everything to the same type internally (bytes in your
> case) and you'd pay a price any time you use it as something else. You
> might take a look anyway.

I have a number of typedef'ed types, and I recently converted them all
to structs.  The nice thing is that once they're structs you can do all
the operator overloading you want (or omit operators that no longer make
any sense), as well as add in conversion functions.

I sort of feel that typedefs, in their current form, are largely useless
because no matter what you want the typedef for, structs seem to be a
better choice.

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/


More information about the Digitalmars-d-learn mailing list