-
Notifications
You must be signed in to change notification settings - Fork 17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Surprising behaviour of enum #142
Comments
wrong webfreak mention lol, anyway here is a good usecase: With enums you can essentially hack in typesafe aliases, which do not implicitly cast to each other, which prevents the users of your libraries from mixing up handles, for example ints in opengl. // typedef types
enum GLTexture : int { init }
enum GLTexture1D : GLTexture { init = GLTexture.init }
enum GLTexture2D : GLTexture { init = GLTexture.init }
enum GLTexture3D : GLTexture { init = GLTexture.init }
// functions using typedefs
extern(C) void glGenTextures(GLsizei n, GLTexture* textures);
extern(C) void glBindTexture(GLenum target, GLTexture texture); Here, GLTexture tex;
glGenTextures(1, &tex); // for pointers the type must exactly match, you couldn't pass a int* nor a GLTexture2D*, however you can always cast in these cases or define multiple overloads of your function
GLTexture2D foo = methodGeneratingATexture2D(); // you could even implicitly cast to GLTexture here, but not the other way around!
glBindTexture(GL_TEXTURE_2D, foo); // works, implicitly casts
glBindTexture(GL_TEXTURE_2D, cast(GLTexture) foo); // works too!
//glBindTexture(GL_TEXTURE_2D, 5); // nope!, don't allow to call with any arbitrary handle or integer
glBindTexture(GL_TEXTURE_2D, cast(GLTexture)5); // yes!, if the developer alreadys explicitly casts, they must know what they are doing But why not use
|
Not surprizing behaviour at all. It is described here https://dlang.org/spec/enum.html#named_enums at point 17.1.5 A named enum member can be implicitly cast to its EnumBaseType, but EnumBaseType types cannot be implicitly cast to an enum type. |
reported by @WebFreaK
The text was updated successfully, but these errors were encountered: