typedefs are useless

Steven Schveighoffer schveiguy at yahoo.com
Tue Dec 4 06:38:40 PST 2007


"Bill Baxter" wrote
> BCS wrote:
>> Steven Schveighoffer wrote:
>>> This may have arisen somewhere before, but...
>>>
>>> Let's say I want a way to create a type that's like a long, but is not 
>>> implicitly convertable from a long.
>> [...]
>>
>> this is getting really close to something I have wanted for some time:
>>
>> typedef real MyReal
>> {
>>    // stuff
>> }
>>
>> it would be like a struct that inherits from a primitive type. The this 
>> would be of the base type and you wouldn't be allowed to add any members. 
>> However this would allow you to do things like overload the operators. 
>> The one things in particular I would like to do would be to overload just 
>> the typing of the operators. This would result in the implementation of + 
>> (for instance) being the same as + on the underlying type, but the type 
>> of the result would be redefined. The point of this would be to allow a 
>> program to restrict the type that could be used. A concrete use case 
>> would be a SIUinits type that would, at compile time, verify unit 
>> correctness, but in the end would result in exactly the same code as if 
>> bare FP values were used.
>>
>> Thoughts?
>
> Why not just make that behavior triggered when you do
>
> struct MyReal : real
> {
> ...
> }
>
> ?

FWIW, you can do stuff like this today by using a struct with a single 
member of the base type you want, but you must define all the operators, but 
there is no implicit cast back to the base type.  A struct is POD, so it 
occupies the same space as the single member, so you get no loss of 
efficiency there.

The other problem is that operators can't be used in constant expressions 
(which is another pet peeve I have about this).  Using a typedef would allow 
operators to be used.

I want to say I really like BCS's idea as it really allows you to redefine 
all aspects of a typedef.  This would be perfect for what I am trying to do.

-Steve 





More information about the Digitalmars-d mailing list