Search code examples
enumsd

Can you refer to a named enum as if it were anonymous in D?


I'm doing a D bridge to a C library, and this has come up with the C code using typedef'd enums that it refers to like a constant, but can name it for function arguments and the like. Example:

enum someLongNameThatTheCLibraryUses
{
    A,
    B,
}

Currently, I must refer to it like so:

someLongNameThatTheCLibraryUses.A;

But I would rather:

A;

I could do this:

alias someLongNameThatTheCLibraryUses a;
a.A;

But I don't want to do that in the library module, so I'd have to do it where it's used, which would be annoying.

Is there a way to do this?


Solution

  • If you would like type safety with anonymous enums, you can create a new distinct type using typedef, and use it as the base type of the anonymous enum. Example:

    typedef int A;
    enum : A
    {
        a1,
        a2,
        a3
    }
    
    typedef int X;
    enum : X
    {
        x1,
        x2,
        x3
    }
    
    void main()
    {
        A a;
        X x;
        x = a;  // Error: cannot implicitly convert expression (a) of type A to X
    }