Is there a way to remove the requirement for parenthesis?

Charles Hixson charleshixsn at earthlink.net
Tue Jan 27 21:57:44 PST 2009


I guess I'm going to do that, but it causes an annoying proliferation of 
casts throughout the program whenever I need to interact with a library 
call that recognized more than one int type.  (The compiler, D2.023 on 
Linux) doesn't seem to properly upcast the type.

Perhaps I'll write separate functions through which to interact with 
library routines.  Unpleasant and messy, but better than scattering 
casts all over the code (as long as they get optimized away).

Daniel Keep wrote:
> Honestly, I can't see what you're trying to accomplish.  It looks like
> you want something that's not called int, but which works exactly like
> an int does, and can be passed as one.
> 
> If you just want another name for "int", you can use an alias.
> 
> From the compiler's POV, there's no difference between "BlockNum" and "int".
> 
>> alias int BlockNum;
>> BlockNum a = 42;
>> someFuncThatTakesAnInt(a);
> 
> If you want to have a type that is an int, but which won't allow itself
> to directly interact with ints, use a typedef.
> 
> Personally, I like this usage for simple numeric values which I don't
> want to accidentally mix with other types.  Yes, it's a bit of a pain to
> do arithmetic, but that's the trade-off you make.
> 
> From the compiler's POV, "BlockNum" and "int" are totally distinct,
> incompatible types that just happen to be the same under the hood.
> 
>> typedef int BlockNum;
>> BlockNum a = cast(BlockNum) 42;
>> someFuncThatTakesAnInt(cast(int) a);
> 
> The last is if you need something that's basically an int, but you want
> it to behave differently.  In that case, a struct with operators is your
> best bet.
> 
> Let's say you wanted to do something like a Meters struct to store
> lengths.  I'd do something like this:
> 
>> struct Meters {
>>     private int value;
>>     int asInt() { return value; }
>>     int asInt(int v) { return value=v; }
>>     // ... operator overloads ...
>> }
>>
>> Meters a; a.asInt = 42;
>> someFuncThatTakesAnInt( a.asInt );
> 
> I can't really offer more than that, since I don't know what it is
> you're trying to accomplish.
> 
>   -- Daniel


More information about the Digitalmars-d-learn mailing list