Skip to content

Instantly share code, notes, and snippets.

@frederikaalund
Created December 29, 2014 01:09
Show Gist options
  • Save frederikaalund/3abeb0a9855881867e31 to your computer and use it in GitHub Desktop.
Save frederikaalund/3abeb0a9855881867e31 to your computer and use it in GitHub Desktop.
// Generate tag. Inspired by C++'s lock tags: http://en.cppreference.com/w/cpp/thread/lock_tag
struct generate_t {};
constexpr generate_t generate;
class texture {
public:
// OpenGL identifies textures by an integer "name". Ref: https://www.opengl.org/sdk/docs/man/html/glGenTextures.xhtml
GLuint name;
// The name "0" is special and denotes an invalid texture. Ref: https://www.opengl.org/sdk/docs/man/html/glDeleteTextures.xhtml
texture() name{0} {}
// name now references an OpenGL texture. Can not fail. Ref: https://www.opengl.org/sdk/docs/man/html/glGenTextures.xhtml
texture( generate_t ) { glGenTextures(1, &name); }
// Non-copyable.
texture( const texture& ) = delete;
// Deletes the OpenGL texture. Ignores the name "0". Ref: https://www.opengl.org/sdk/docs/man/html/glDeleteTextures.xhtml
~texture() { glDeleteTextures(1, &name); } //
// Convenience cast.
operator GLuint() const { return name; }
};
int main () {
// Default-construct a texture. No actual OpenGL calls are issued
texture my_non_texture;
// Generate-construct a texture.
texture my_actual_texture{generate};
// Use the actual texture. Just straight-up OpenGL calls
glBindTexture(GL_TEXTURE_2D, my_actual_texture);
// ...All textures are deleted when out of scope. Never forget a glDeleteTextures call again!
}
Copy link

ghost commented Dec 16, 2015

Thanks :) I've been looking for a design like this ! Though I would use unique-ptr-s with deleter classes...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment