C++ 完全通用的事件调度器

c++ completely generic event dispatcher

我再次尝试更好地解释我将实现的目标。
我想做这样的事情(受 Unity 的 UnityEvent 启发):

Public 在某些 class 中声明的“变量”:

GameEvent<> OnEnemySpawn = GameEvent<>();
GameEvent<string> OnPlayerSpawn = GameEvent<string>(); 
GameEvent<string, float> OnEnemyDie = GameEvent<string, float>();

推荐其他 classes 订阅他们的方法:

...
enemySpawner.OnEnemySpawn.Subscribe(IncreaseEnemyAliveCountByOne);
...
playerSpawner.OnPlayerSpawn.Subscribe(NewPlayerSpawned);
...
enemy.OnEnemyDie.Subscribe(IncreasePlayerScore);
...
// Subscribed methods declaration
void IncreaseEnemyAliceCountByOne() { ... }
void NewPlayerSpawned(string playerName) { ... }
void IncreasePlayerScore(string playerName, float scoreToAdd) { ... }

然后GameEvent class就可以通知事件发生了:

...
OnEnemySpawn.Notify();
...
OnPlayerSpawn.Notify(newPlayer.PlayerName);
...
OnEnemyDie.Notify(playerKiller.PlayerName, scoreOnKill);
...

实际上,我实现了创建这个class的声明和订阅部分:

templace<class ... T>
class GameEvent
{
private:
    std::vector<std::function<void(T...)>> _subscribers;

public:
    void Subscribe(std::function<void(T...)> newSubscriber)
  {
    _subscribers.push_back(newSubscriber);
  }
}

让我发疯的是如何实现通知方法。我怎么知道我收到了多少个参数以及它们有哪些类型

void Notify(T...)
{
    for (std::function<void(T...)> subscriber : _subscribers)
  {
    
  }
}

我现在希望这是一个有效的问题,因为我在这背后失去了理智

明显的方法有什么问题?

void Notify(T... args)
{
    // note: no need to write the type if it's quite long
    // note: & means the std::function isn't copied
    for (auto const& subscriber : _subscribers)
    {
        subscriber(args...);
    }
}