opEquals() non-standard return type

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Jan 23 15:28:02 UTC 2019


On Wednesday, January 23, 2019 8:19:06 AM MST Jacob Shtokolov via 
Digitalmars-d-learn wrote:
> Hi,
>
> I'm trying to check whether it's possible to implement Python's
> SQLAlchemy-like query syntax in D, but I get stuck a bit.
>
> Here is a simple example of what I want to achieve:
>
> ```
> auto result = User.filter(User.id == 10);
> result = User.filter(User.name == "John");
> result = User.filter(User.age > 18);
> ```
>
> Expressions like `User.id == 10`, `User.age > 18`, etc. should
> return a struct instead of a bool (let's call it `struct
> BinaryExpression`).
>
> So I'm making the two versions of opEquals: one returns a
> BinaryExpression, and the second - a boolean value.
>
> However, when I want to use the same expression for the `if`
> operator, the compiler cannot decide what function to call and
> shows an error: "overloads bool(int b) and BinaryExpr!int(int b)
> both match argument list for opEquals".
>
>
> I'm wondering, is that possible to declare multiple versions of
> opEquals() and evaluate them in the different places depending on
> return type?
>
> Here is my test code to check: https://run.dlang.io/is/yTFHWp
> Gist:
> https://gist.github.com/run-dlang/67ec42ca73d56d310e8ae765fabede69
>
> Thanks!

D's operator overloading is specifically designed around the idea that
overloaded operators are supposed to act like the operators on the built-in
types and that they _not_ be used for building syntax. opEquals is supposed
to only return bool. If you attempt to make it return pretty much anything
else, you're begging for trouble.

But regardless of the specifics of operator overloading in D, D does not
support overloading _any_ functions on the return type. Overloading is only
done based an a function's arguments. You've declared two overloads with the
exact same types for all of their parameters such that they only differ by
their return type, and you can't do that in D.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list