flyweight.hpp 685 B

123456789101112131415161718192021222324252627282930313233
  1. //
  2. // flyweight.hpp
  3. // gameutils
  4. //
  5. // Created by Sam Jaffe on 5/19/19.
  6. //
  7. #pragma once
  8. #include <unordered_map>
  9. #include "identity.hpp"
  10. template <typename T> class flyweight {
  11. private:
  12. static std::unordered_map<unsigned int, T> actual_;
  13. public:
  14. const unsigned int id;
  15. public:
  16. flyweight(unsigned int id, T actual) : id(id) {
  17. actual_.emplace(id, std::move(actual));
  18. }
  19. flyweight(identity<T> actual) : id(actual.id) {}
  20. T const & actual() const { return actual_.find(this->id)->second; }
  21. friend bool operator==(flyweight lhs, flyweight rhs) {
  22. return lhs.id == rhs.id;
  23. }
  24. };
  25. template <typename T> std::unordered_map<unsigned int, T> flyweight<T>::actual_;