Overriding "in" operator

Mafi mafi at example.org
Fri Mar 4 08:06:29 PST 2011


Am 04.03.2011 17:01, schrieb Magnus Lie Hetland:
> I'm writing a collection with functionality for membership checking. I
> thought it would be nice to use the "in" operator. In the docs for
> std.collections I surmise that this is the standard way to go. From the
> source code, I see there's no special opIn, but that it can be done with
> the more general...
>
> bool opBinary(string op)(T k) if (op == "in") {
> ...
> }
>
> Here T is, of course, a compile-time argument of the surrounding struct
> or class.
>
> So ... this is used in the the Phobos source in the DMD 2.052 distro (if
> I'm not mistaken), but I can't get dmd 2.052 to accept it? I keep
> getting the error message "Error: rvalue of in expression must be an
> associative array, not Foo!(uint)".
>
> I guess either that this is a recent feature -- I didn't see it
> mentioned in Andrei's book -- and that my Phobos source is too recent
> for my dmd ... or that I'm doing something wrong elsewhere in my code,
> preventing the operator overloading to take force. Suggestions/solutions?-)
>

If you try to use it in the manner of `something in 
classWhichDefinesThisOpBinary` then it doesn't work because operator 
overloading normally overloads on the left operand (ie something). Use 
opBinaryRight(string op)(...) if(...) to get it working.

Mafi


More information about the Digitalmars-d-learn mailing list