Required constness of opEquals (and opCmp) ?
Jonathan M Davis
jmdavisProg at gmx.com
Wed Jan 2 01:23:03 PST 2013
On Wednesday, January 02, 2013 10:07:30 monarch_dodra wrote:
> I was wondering: Does Phobos require that user defined opEquals
> (and opCmp) be const?
>
> If someone wants to define a non-const opAssign, I'd say that's
> their problem, but are we (phobos) expected to support it?
>
> The reason I ask is because adding support for this means that
> every type that wraps any other type (which is basically...
> everything), would be required to implement *two* signatures for
> opAssign. Not only that, they'd both have to be conditionally
> implemented...
>
> The context of this question is:
> http://forum.dlang.org/thread/urzkfsaqvodhhcnqeoet@forum.dlang.org
>
> Basically, a DList of tuples: Problem:
> DList has a "const correct" opEquals, but Tuple's isn't. It has:
> //----
> bool opEquals(R)(R rhs); //1
> bool opEquals(R)(R rhs) const; //2
> //----
>
> The problem is that //2 should really be:
> //----
> bool opEquals(R)(const R rhs) const; //2
> //----
>
> However, my question is: Should we even provide //1 at all? Is it
> fine if I deprecate this signature?
>
> My opinion is that supporting non-const opEquals makes no real
> sense, and adds a lot of useless complexity (and inconsistency)
> to the code. At best, it means silently accepting erroneous
> code... Until it explodes in someone else's face...
>
> Opinions?
This has been discussed quite a bit with regards to classes. We need to be
able to support both const and non-const versions of opEquals, opCmp, toHash,
and toString. D's const is restrictive enough that it prevents stuff like
caching and lazy loading from working properly with const, meaning that we
_cannot_ require const. Yes, in most cases, opEquals should be const, but it
can't always be, so we can't assume that it is.
However, there's a good chance that inout could be used instead if you're
worried about duplicating code.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list