On Wed, Sep 21, 2016 at 08:53:06PM +0000, HaraldZealot via Digitalmars-d wrote:
> On Wednesday, 21 September 2016 at 19:01:40 UTC, Timon Gehr wrote:
> > 
> > Basically, the rationale is: external operators cannot be used in
> > generic code that does not import the module defining the operators.
> 
> Could you give some elaborate example, for now I can't imagine what
> your mean.

Here's a simple example:

        // usertype.d
        module usertype;
        struct UserType { ... }
        auto opBinary(string op : "+")(UserType u1, UserType u2) { ... }

        // generic_code.d
        module generic_code;
        auto algorithm(T,U)(T t, U u) {
                return t + u;
        }

        // main.d
        module main;
        import usertype;
        import generic_code;
        void main() {
                UserType u1, u2;
                auto r = u1 + u2;               // OK
                auto s = algorithm(u1, u2);     // NO GOOD
        }

The problem here is that generic_code.d doesn't (and shouldn't!) import
usertype.d, so usertype.opBinary is not visible in generic_code.d. So
when algorithm() tries to look up the '+' operator in `t + u`, it can't
find the declaration and fails.  There is no way to find the correct
opBinary() because it's not part of UserType, so algorithm() has no way
to access that symbol.

Using the operator in module main is OK, because main (rightfully)
imports usertype.d, so the operator is visible. But any generic code
that main imports will have a problem because they can't (and
shouldn't!) know ahead of time which modules contain the declaration
they need.

In C++ this problem is solved using ADL, but ADL brings with it other
problems, the root of which is that it breaks module encapsulation.

There's actually some instances of this problem (w.r.t. UFCS) in Phobos,
that currently requires ugly workarounds like importing modules that the
generic code really shouldn't be depending on.


T

-- 
Computerese Irregular Verb Conjugation: I have preferences.  You have biases.  
He/She has prejudices. -- Gene Wirchenko

Reply via email to