1

I'm writing a program in OpenGL, and there's going to be custom events that are going to happen, ex. when a player hits an obstacle or takes a step. What I want to do is:

Have a singleton class named something like "EventBroadcaster." The broadcaster will get fed events from around the program. Then, when it receives an event, it will send it to all the listeners ("EventListener" objects) with a void* containing a struct which holds the event's information. The EventListener objects can then use their own custom callback function to handle the different types of events. Now, I want to avoid using void* if it all possible, so...

...question is, how can I do this with a template interface?

4

2 回答 2

2

如果您只想避免因为使用 void 指针而丢弃类型信息,则可能需要查看boost::any

于 2012-12-13T23:30:56.573 回答
1

将所有内容都转换为 void* 然后返回很容易出错。看看boost::signals其他一些信号/槽库。它可能会帮助您避免丢弃类型信息。

一个类可以公开一个槽然后调用它。例如,可能有一个像void PlayerMovedTo( Point position ). 其他类可以连接到该插槽,并在发送信号时收到通知。

这是信号/插槽机制一般如何工作的粗略草图:

class Game {
public:
  Signal<void (float, float)> PlayerMovedTo;

  void update() {
    if ( downKeyPressed ) {
       y += 10;
       PlayerMovedTo( x, y ); // Tell everyone about it
    }
  }
};


class Mine {
public:
  Mine() {
    // There can be many mines, all connected to the one signal.
    game.PlayerMovedTo.connect( this, &Mine::playerMoved );
  }

  void playerMoved( float x, float y ) {
    if ( distance( this->x, this->y, x, y ) < 10 ) {
      boom();
    }
  }
}; 
于 2012-12-13T23:47:12.883 回答