I'm trying to implement better key state detection on a wrapper class for a GLFW window. I needed to make sure that if my key state was continually set as pressed, certain actions wouldn't re-trigger. So I encapsulated the idea of rising, falling, floor and ceiling edge triggers. The issue is that I won't necessarily need all triggers on all compiled parts of code. so I came up with the following solution:
class Window{
public:
GLFWwindow *m_window_ptr = nullptr;
//...
bool isKeyPressed(int key) const{
return glfwGetKey(m_window_ptr, key) == GLFW_PRESS;
}
bool isKeyReleased(int key) const{
return glfwGetKey(m_window_ptr, key) == GLFW_RELEASE;
}
enum class KeyState {
pressed,
released
};
enum class SignalEdge {
rising,
falling,
floor,
ceiling,
};
template<int key_t>
SignalEdge getKeyState() {
static KeyState last_key_state = KeyState::released;
switch (last_key_state) {
case KeyState::released:
if (isKeyPressed(key_t)) {
last_key_state = KeyState::pressed;
return SignalEdge::rising;
} else {
return SignalEdge::floor;
}
break;
case KeyState::pressed:
if (isKeyReleased(key_t)) {
last_key_state = KeyState::released;
return SignalEdge::falling;
} else {
return SignalEdge::ceiling;
}
break;
}
}
template<int key_t>
bool isKeyRisingEdge() {
return getKeyState<key_t>() == SignalEdge::rising;
}
};
Only to realize that I'll need this per window object, so static variables inside each getKeyState template instantiation will apply to every window in GLFW.
My only way of avoiding this then, is to use member variables per templated key type but I don't want to spend the effort to map every single key type in my class just to set a state variable for each. I would like to automatically map per-object variables to the existence of a given template function, ie exactly what I've set up here, but where the state is saved per GLFW window object.
If I eliminate manually mapping the GLFW enum ints, I'm not sure what I can do, I thought about variable templates but I'm not seeing a path forward on that either ( how would I have a variable only exist on template instantiation of a function?). The only other option I see is storing a dynamically alocated array of states as the member function static variable, internally storing a incremented index per each window object used to index into the static variable array, or do the opposite with the functions but that seems messy? Is there another way I can do this at compile time with templates?