Bug 13352 – Algebraic does not support binary arithmetic when omitting small number types

Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P1
Component
phobos
Product
D
Version
D2
Platform
Other
OS
All
Creation time
2014-08-22T09:26:00Z
Last change time
2014-09-11T08:53:45Z
Keywords
pull
Assigned to
nobody
Creator
sludwig

Comments

Comment #0 by sludwig — 2014-08-22T09:26:41Z
For example, when defining Algebraic!(long) and then trying to add two such values, or an algebraic with a raw number, opArithmetic will try to instantiate an Algebraic!(long) with an int, which fails compilation. --- alias TP = Algebraic!(long); auto a = TP(1L); auto b = TP(2L); assert(a + b == 3L); // error assert(a + 2 == 3L); // error assert(1 + b == 3L); // error ---
Comment #1 by sludwig — 2014-08-22T09:44:11Z
Comment #2 by bearophile_hugs — 2014-08-22T10:18:31Z
assert(a + b == 3L); // error assert(a + 2 == 3L); // error assert(1 + b == 3L); // error I think giving an error is correct. An algebraic data type is not meant to be transparent to arithmetic operations, it's a way to bundle alternative types.
Comment #3 by sludwig — 2014-08-22T10:39:36Z
Well, "Algebraic!(uint, int, long)" would have worked. The intention of VariantN definitely is to make all operations transparently available, if you look at the source code. I also don't see a reason why that would be harmful. On the other hand, it can be extremely useful. See for example the new std.data.json proposal, which is the reason for this bug report. It allows "JSONValue" to be used in a much more convenient way.
Comment #4 by github-bugzilla — 2014-09-11T08:53:45Z
Commits pushed to master at https://github.com/D-Programming-Language/phobos https://github.com/D-Programming-Language/phobos/commit/cb5d83dad9c22e973f494006e874771eddf833dc Fix issue #13352 - Only perform Algebraic arithmetic with allowed types. Adds a static check allowed!T before trying any particular numeric type. Also checks for an exact type match in case of a raw (non-Variant) operand and prefers that to one of the fixed numeric types. Finally, it loosens the restriction for opArithmetic to only work for equal Variant types. Conflicts: std/variant.d https://github.com/D-Programming-Language/phobos/commit/67db0d68a78d48b0c2b3c2b6cbe9b8ee8ad855d6 Merge pull request #2452 from s-ludwig/issue_13352 Fix issue #13352 - Only perform Algebraic arithmetic with allowed types.