Casting Structs
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat May 31 15:25:29 PDT 2014
On 05/31/2014 02:11 PM, Paul D Anderson wrote:
> I'm working on the decimal number package for D. A decimal is a struct
> with precision, max exponent and rounding mode parameters:
> "Decimal!(PRECISION, MAX_EXPO, ROUNDING)". I was trying to overload the
> opCast operator for this struct and I found that it does not seem
> necessary. I can cast decimals with different precisions, etc., back and
> forth without overloading opCast.
>
> This code works:
>
> alias dec9 = Decimal!(9,99);
> alias dec10 = Decimal!(10,99);
>
> dec9 bingo = dec9("123.45");
> dec10 little = cast(dec10(bingo));
You meant cast(dec10)(bingo).
> assert(little == dec10("123.45"));
>
> Is this expected behavior?
>
> Paul
>
That is surprising. I've discovered that if the template has members
that depend on a template parameter than the code fails to compile. I
think it should fail to compile in other cases as well because a
separate instantiation of a template is a separate type potentially with
completely different invariants.
Here is reduced code that fails to compile:
struct Decimal(int A, int B)
{
int[A] arrA;// Replace this with something that does not depend on a
// template parameter and the code compiles.
this(string)
{}
}
alias dec9 = Decimal!(9,99);
alias dec10 = Decimal!(10,99);
void main()
{
dec9 bingo = dec9("123.45");
dec10 little = cast(dec10)(bingo);
assert(little == dec10("123.45"));
}
Ali
More information about the Digitalmars-d-learn
mailing list