Why this doesn't produce an error or works as expected?
monkyyy
crazymonkyyy at gmail.com
Fri Jul 4 17:34:59 UTC 2025
On Friday, 4 July 2025 at 17:15:48 UTC, partypooper wrote:
> ```d
> struct Vector
> {
> float x, y;
>
> Vector opBinary(string op)(inout Vector rhs) const if (op
> == "+")
> {
> return Vector(mixin("x", op, "rhs.x"), mixin("y", op,
> "rhs.y"),);
> }
>
> ref Vector opOpAssign(string op)(inout Vector rhs) if (op
> == "+" || op == "-")
> {
> mixin("x", op, "=rhs.x;");
> mixin("y", op, "=rhs.y;");
> return this;
> }
> }
>
> struct A
> {
> Vector _pos, _dest;
>
> this(Vector pos)
> {
> this._pos = pos;
> this._dest = pos;
> }
>
> Vector pos() => _pos;
> Vector pos(Vector v)
> {
> _dest.x = v.x;
> _dest.y = v.y;
> return _pos = v;
> }
> }
>
> void main()
> {
> import std.stdio : writeln;
>
> A a = A(Vector(10, 20));
> a.pos += Vector(1, 2); // silently does nothing
> writeln(a);
> }
> ```
>
> How I can make it to work, if it is possible? Or else how to
> make compiler error/warning for such cases?
if you add ref to line 28 it works; there wont be a reasonable
way to make an error happen, you just have to know when to do
refness
More information about the Digitalmars-d-learn
mailing list