Hi All,
This is more of an aesthetic problem I have.
My project (in bold the class names): Creating a simple game engine using OpenGL (Qt style)
There is a big
Game class, which handles most of the OpenGL stuff. The plan is: the user inherits the
Game class to extend it (Let's call the new Class
MyGame).
Game inherits from
EventManager (a singleton). And here is where my problem comes in: I want the user to be able to create a method; let's call it
void keyPressEvent(Key key)
This method must not be static (else it would be pretty useless to the user). So the function pointer will be in the format
void (MyGame::*keyPressEvent)(Key key)
Now I have in the class
Game a function that will pass the user-defined function to the singleton (
EventManager) which handles the callbacks. (In order to do that the functions to pass on to OpenGL have to be static!)
And from that it should also be clear why
EventManager is a singleton. Now while passing the function pointer on to the method
void setKeyboardFunc(void (MyGame::*func)(Key key))
in
Game I ran in to a problem: what is
MyGame?
I found some solutions which are only semi-elegant, but I'm sure there is a more "beautiful" one out there.
My solutions:
- reinterpret_casting it to
Game (which feels kinda awkward to do imho)
- template (i.e. Game<MyGame>) which will be able to tell me the type
- creating an abstract function pointer (with the use of variadic templates; see below)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
template <typename ret, typename... args>
class AbstractFptr {
public:
virtual ret operator()(args... a) = 0;
};
template <class C, typename ret, typename... args>
class Fptr : public AbstractFptr<ret, args...> {
private:
C& obj;
ret (C::*fun)(args...);
public:
Fptr(C& o, ret (C::*f)(args...))
: obj(o), fun(f) {}
ret operator()(args... a) {
(obj.*fun)(a...);
}
};
|
Is there some other way to elegantly do this (without variadic templates ;-) )??
Thanks in advance!