How to simulate a new type

Charles Hixson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 14 18:02:11 PDT 2015



On 05/14/2015 01:42 PM, Laeeth Isharc via Digitalmars-d-learn wrote:
> On Thursday, 14 May 2015 at 18:42:56 UTC, Charles Hixson wrote:
>> What are the downsides to simulating a new type with a struct.
>>
>> What I have in mind is something along the lines of:
>>
>> struct myType
>> {  uint64_t  value;
>> }
>>
>> The goal of this type is to prevent accidental conversions from 
>> myType into ints, uint64_ts, etc.
>
> http://dlang.org/phobos/std_typecons.html#.Typedef
>
Yes, that looks as if it would do the job, but what are its advantages 
over a simple struct?  I'd be hesitant to try to predict the RAM layout 
of a templated variable, but it's my understanding that a struct has 
neither compile time nor runtime penalties over a simple variable, and 
that it doesn't increase RAM comsumption when included within another 
struct, or in a static array.

What I was really wondering was whether the limitation of access caused 
by enclosing a variable within a struct was worth the benefit.  
Templates add a whole 'nother layer of complexity.  For that matter I 
was thinking that, if I so chose, I could at some point add limits along 
the lines of Ada's types.  I like being *able* to define conversions for 
types, but frequently I'd rather not have them arbitrarily assumed.  
Otherwise I'd just use alias, which almost does what I want.  (E.g., one 
thing I might eventually want to do is use a couple of bits at the top 
of the uint64_t as flags, so if I did define operations I'd need to be 
able to mask the flag bits off before the operation and reapply them to 
the result, in some defined way of combining the flags.  Not good if 
sometimes the value is going to be automatically reinterpreted as a 
plain number.)


More information about the Digitalmars-d-learn mailing list