xenia/src/poly/delegate.h

51 lines
1.3 KiB
C
Raw Normal View History

/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
2014-12-20 17:49:11 +01:00
#ifndef POLY_DELEGATE_H_
#define POLY_DELEGATE_H_
#include <functional>
#include <mutex>
#include <vector>
2014-12-20 17:49:11 +01:00
namespace poly {
// TODO(benvanik): go lockfree, and don't hold the lock while emitting.
2014-12-20 17:49:11 +01:00
template <typename... Args>
class Delegate {
public:
2014-12-20 17:49:11 +01:00
typedef std::function<void(Args&...)> Listener;
void AddListener(Listener const& listener) {
std::lock_guard<std::mutex> guard(lock_);
listeners_.push_back(listener);
}
void RemoveAllListeners() {
std::lock_guard<std::mutex> guard(lock_);
listeners_.clear();
}
2014-12-20 17:49:11 +01:00
void operator()(Args&... args) {
std::lock_guard<std::mutex> guard(lock_);
for (auto& listener : listeners_) {
2014-12-20 17:49:11 +01:00
listener(args...);
}
}
private:
std::mutex lock_;
2014-07-14 06:15:37 +02:00
std::vector<Listener> listeners_;
};
2014-12-20 17:49:11 +01:00
} // namespace poly
2014-12-20 17:49:11 +01:00
#endif // POLY_DELEGATE_H_