need clarification: will typedef, C struct initialization, etc.

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Jun 4 10:13:12 PDT 2010


On 06/04/2010 06:38 AM, Lionello Lunesu wrote:
> On 4-6-2010 1:17, Adam Ruppe wrote:
>> ....
>> This strikes me as being a supremely elegant solution, not a hack.
>
> struct Typedef( T, T init = T.init, Type type = Type.Sub, string _f =
> __FILE__, int _l = __LINE__ ) { ...
>
> Yes, that's a hack.
>
> And it's great that we can do sub, super, independent and parallel, but
> the question is: are they needed?
>
> I thought I had found a compelling use case for typedef. Perhaps,
> instead of throwing it out because it was ill defined, we should define
> what's it supposed to solve and then make sure that's exactly what it
> does, and nothing more.

The problem is, there's not only one good use. Walter and I identified 
at least a gew. The built-in typedef fails all examples below because it 
was very superficially designed.

1. Something that's just like another type yet "parallel" with it. This 
is good for abstractions that encode different units of measurement that 
aren't supposed to be mixed.

ParallelTypedef!double Miles;

Such a type should accept explicit initialization from a regular double:

auto dist = Miles(3.2);

However it shouldn't accept initialization from another parallel typedef:

ParallelTypedef!double Kms;
auto dist1 = Kms(4);
auto dist2 = Miles(dist1); // no

Arithmetic operations should only work within Miles but not mixing Miles 
with other types. Here's where things already get complicated - you do 
want to allow some operations between Miles and double (e.g. "*"), in 
some others you don't (e.g. "+"). Here's where a library facility would 
help:

ParallelTypdef!(double, "allow_arithmetic", "allow_mixed:*,/,%")
     Miles;

2. Opaque "handle" types that can be used with overloading. The base 
type of the typedef is just the storage strategy:

OpaqueTypedef!int FileHandle;

Such a typedef supports no arithmetic and no implicit conversions. You 
can explicitly initialize it from an int and you can cast it back to it 
using an explicit cast.

3. Proper subtype. Create a true subtype of a type that allows explicit 
initialization from the type and implicit conversion to the type.

SubtypeTypedef!Exception MyException;

4. Proper supertype. The base type implicitly converts to the introduced 
type, but not vice versa.

SupertypeTypedef!uint Bits;



Andrei


More information about the Digitalmars-d mailing list