我再一次尝试更好地解释我会取得什么成就。
我想做一件这样的事情(灵感来自团结的UnityEvent):
在某些类中声明的公共“变量”:
GameEvent<> OnEnemySpawn = GameEvent<>();
GameEvent<string> OnPlayerSpawn = GameEvent<string>();
GameEvent<string, float> OnEnemyDie = GameEvent<string, float>();某些其他类订阅其方法的引用:
...
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类将能够通知发生的事件:
...
OnEnemySpawn.Notify();
...
OnPlayerSpawn.Notify(newPlayer.PlayerName);
...
OnEnemyDie.Notify(playerKiller.PlayerName, scoreOnKill);
...实际上,我实现了创建该类的声明和订阅部分:
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)
{
}
}我希望这是一个有效的问题,因为我在这背后失去了理智
发布于 2022-04-07 12:57:57
显而易见的方法有什么问题?
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...);
}
}https://stackoverflow.com/questions/71782254
复制相似问题