Last active
May 15, 2020 01:06
-
-
Save natanaeljr/e70c23cdac4e1bc79b5a7cbfdd78c558 to your computer and use it in GitHub Desktop.
Turn runnable code into property objects [Example with GLFW window]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <utility> | |
#include <GLFW/glfw3.h> | |
#include <unistd.h> | |
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {} | |
static void error_callback_glfw(int error, const char* description) {} | |
static void framebuffer_size_callback(GLFWwindow* window, int width, int height) {} | |
struct BasicProperties { | |
int width; | |
int height; | |
const char* title; | |
}; | |
auto KeyCallback(GLFWkeyfun keyfun) { | |
return [keyfun](GLFWwindow* window) { | |
glfwSetKeyCallback(window, keyfun); | |
}; | |
} | |
auto FramebufferSizeCallback(GLFWframebuffersizefun cb) { | |
return [cb](GLFWwindow* window) { | |
glfwSetFramebufferSizeCallback(window, cb); | |
}; | |
} | |
auto MakeContextCurrent() { | |
return [](GLFWwindow* window) { | |
glfwMakeContextCurrent(window); | |
}; | |
} | |
class Window { | |
public: | |
template<typename ...Props> | |
static Window with_properties(BasicProperties basics, Props&&... props) { | |
Window window(basics); | |
(props.operator()(window.m_window), ...); | |
return window; | |
} | |
private: | |
Window(BasicProperties basics) { | |
m_window = glfwCreateWindow(basics.width, basics.height, basics.title, NULL, NULL); | |
if (!m_window) { | |
fprintf(stderr, "Window or OpenGL context creation failed.\n"); | |
} | |
} | |
private: | |
GLFWwindow* m_window; | |
}; | |
//////////////////////////////////////////////////////////////////////////////// | |
int main() | |
{ | |
if (!glfwInit()) { | |
fprintf(stderr, "GLFW initialization failure.\n"); | |
return 2; | |
} | |
auto window = Window::with_properties( | |
BasicProperties{ .width=1280, .height=720, .title="Graphics Programming" }, | |
KeyCallback(key_callback), | |
FramebufferSizeCallback(framebuffer_size_callback), | |
MakeContextCurrent() | |
); | |
sleep(2); | |
glfwTerminate(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment