SHARE
TWEET

Untitled

a guest Sep 20th, 2019 90 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #pragma once
  2. #include <string>
  3. #include <map>
  4. #include <assert.h>
  5.  
  6. template <typename Resource, typename Identifier>
  7. class ResourceHolder
  8. {
  9. public:
  10.  
  11.     void load(Identifier id, const std::string& fileName);
  12.  
  13.     template<typename Parameter>
  14.     void load(Identifier id, const std::string& fileName, const Parameter& secondParam);
  15.  
  16.     Resource& get(Identifier id);
  17.     const Resource& get(Identifier id) const;
  18.  
  19. private:
  20.  
  21.     std::map<Identifier, std::unique_ptr<Resource>> _resourceMap;
  22.  
  23. };
  24.  
  25. // Implementation
  26. // ---------------
  27.  
  28. template <typename Resource, typename Identifier>
  29. void ResourceHolder<Resource, Identifier>::load(Identifier id, const std::string& fileName)
  30. {
  31.     std::unique_ptr<Resource> resource(new Resource());
  32.     if (resource->loadFromFile(fileName) == false)
  33.     {
  34.         throw std::runtime_error("ResourceHolder failed to load" + fileName);
  35.     }
  36.  
  37.     auto inserted = _resourceMap.insert(
  38.         std::make_pair(id, std::move(resource)));
  39.  
  40.     assert(inserted.second);
  41. }
  42.  
  43. template<typename Resource, typename Identifier>
  44. Resource& ResourceHolder<Resource, Identifier>::get(Identifier id)
  45. {
  46.     auto found = _resourceMap.find(id);
  47.     assert(("Could not find resource in map!", found != _resourceMap.end()));
  48.     return *found->second;
  49.  
  50. }
  51.  
  52. template<typename Resource, typename Identifier>
  53. const Resource& ResourceHolder<Resource, Identifier>::get(Identifier id) const
  54. {
  55.     auto found = _resourceMap.find(id);
  56.     assert(("Could not find resource in map!", found != _resourceMap.end()));
  57.     return *found->second;
  58.  
  59. }
  60.  
  61. template <typename Resource, typename Identifier>
  62. template <typename Parameter>
  63. void ResourceHolder<Resource, Identifier>::load(
  64.     Identifier id,
  65.     const std::string& fileName,
  66.     const Parameter& secondParam)
  67. {
  68.     std::unique_ptr<Resource> resource(new Resource());
  69.     if (resource->loadFromFile(fileName, secondParam))
  70.     {
  71.         throw std::runtime_error("ResourceHolder failed to load" + fileName);
  72.     }
  73.  
  74.     auto inserted = _resourceMap.insert(
  75.         std::make_pair(id, std::move(resource)));
  76.  
  77.     assert(inserted.second);
  78. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top