Operator overloading or alternatives to expression templates

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Fri Sep 11 16:47:42 PDT 2015


On 09/11/2015 03:40 PM, Martin Nowak wrote:
> I find the reasons for turining down my ER a bit moot.
>
> [Issue 14593 – operator overloading can't be used with expression
> templates](https://issues.dlang.org/show_bug.cgi?id=14593)
>
> AFAIK expression templates are the primary choice tom implement SIMD and
> matrix libraries.
> And I still have [this idea](http://dpaste.dzfl.pl/cd375ac594cf) of
> implementing a nice query language for ORMs.

Expression templates are interesting, but from experience with them in 
C++ they're more trouble than they're worth. They haven't made much 
inroads in C++ outside exotic libraries because (a) they have odd and 
random limitations and corner cases and (b) they have really byzantine 
failure modes. Just look at any non-toy-example C++ use of ETs - it's 
completely bizarre.

I'd say if a language wants to support expression templates properly, 
there's a lot of careful design to get into it, way beyond intercepting 
operators. Like e.g. C#/LINQ. I don't think D is prepared for that.

> D currently doesn't allow to override some operators like < <= > >= &&
> || !=.
>
> At least the comparison operators are really limiting, e.g. it's not
> possible to efficiently implement logical indexing.
>
> vec[vec < 15], vec[vec == 15], vec[(vec != 15) & (vec > 10)]
>
> Also opCmp is less efficient to implement than opBinary!"<" for many
> types. Generally any good implementation of an algorithm should only
> require a less operator, not a full ordering opCmp.
>
> The short circuit operators && and || have a special semantic and can't
> be easily, but there is & and | so it's not really required.
>
> Now expression templates make an awful DSL when being used to create a
> HTML formatter, but when the original semantic of the operators is
> preserved they are really powerful b/c the compiler already handles
> typechecking, operator precedence, and captures variables.
>
> Does anyone have a different idea how to make a nice query language?
> db.get!Person.where!(p => p.age > 21 && p.name == "Peter")

There's two canonical ways to do that.

1. Use lambdas, which seem to already do what you want:

db.get!Person.filter!(p => p.age > 21 && p.name == "Peter")

The way this'd go, the db.get!Person() call returns an input range of 
Person. Presumably introspection is being used to bind fields in the 
query such as "age" and "name" to static field names in struct Person. 
Then good old std.algorithm.filter takes care of the rest.

2. If you want to embed real SQL into D, use string-based DSLs.


Andrei



More information about the Digitalmars-d mailing list