D lang enum security type in comparison

This situation is error prone:

enum A{x=0};
enum B{y=0};

if (A.x == B.y) {
    writeln("Indeed.");
}

I compare enum vals of different enumerations ... happens to me by mistake.

How can I make these listings safe? those. make dmd at least warn me that i am comparing 2 different enumerations?

I understand that both values ​​are raised to "int" before comparison.

Is there a way without creating a new type to help me with this?

edit: official DMD error report related to this problem: https://issues.dlang.org/show_bug.cgi?id=6227 (PR: https://github.com/dlang/dmd/pull/6444 )

+4
source share
3 answers

. :

bool compare(T)(T a, T b) if (is(T == enum)) {
    return a == b;
}

, . , , opEquals , , , . , enum , - .

+1

- . , ==:

import std.stdio;

struct ExtendedEnumeration(E) if (is(E==enum))
{
    E e;
    alias e this;
    bool opEquals(Rhs)(Rhs rhs){
        static if (is(Rhs == typeof(this)))
            return rhs == e;
        else static if (is(Rhs == E))
            return rhs == e;
        else
            assert(0, "unsupported type for comparison argument");
    }
}

void main(string args[])
{
    enum A{x}
    enum B{y=0}
    ExtendedEnumeration!A a; 
    ExtendedEnumeration!B b;
    writeln(a == b);
}

.

core.exception.AssertError@C:...\temp_0186F968.d(13):

...

false, rhs ... , .

+1

Just spitballing, but you can write a comparison function and use it instead of an operator ==. Enum type checking for functional parameters is more stringent:

enum A{x}
enum B{y=0}

bool compare(A a, A b) {
        return a == b;
}

void main() {
        import std.stdio;
        A a = A.x;
        if (compare(a, B.y)) {
            writeln("Indeed.");
        }
}

test100.d (11): Error: function test100.compare (A a, A b) cannot be called using argument types (A, B)

this kind of sux tho.

0
source

All Articles