Skip to content

Associative Arrays Class Key Type #4245

Open
@fieldvoid

Description

@fieldvoid

The spec says that for class types to be used as keys in associative arrays, two member functions must be overridden - opEquals and opHash. However the compiler accepts code where the class has not overridden these two member functions, providing some default implementation.
I think that the spec might be outdated - if so it needs to be updated to specify that classes may provide custom implementations of opHash and opEquals, and to clarify whether having one member function overriden necessitates also overriding the other.

Please see example below:

import std.stdio;

class Foo {
}

class Bar : Foo {
}

void main () {
    bool[Foo] set;
    
    Foo a = new Foo;
    Foo b = new Bar;
    
    set[a] = true;
    set[b] = true;
    
    if (a in set) {
        "%s is in set".writefln(a);
    }
    
    if (b in set) {
        "%s is in set".writefln(b);
    }
    
    set.remove(b);
    
    if (b !in set) {
        "%s is not in set.".writefln(b);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions