fork download
  1. #include <iostream>
  2. #include <cassert>
  3.  
  4. struct ResourceHandle
  5. {
  6. typedef unsigned Id;
  7. static const Id NULL_ID = 0;
  8. ResourceHandle() : id(NULL_ID) {}
  9.  
  10. bool isNull() const
  11. { return id == NULL_ID; }
  12.  
  13. Id id;
  14. };
  15.  
  16. template <typename THandle, typename THandleInterface>
  17. struct Resource
  18. {
  19. typedef THandle Handle;
  20. typedef THandleInterface HandleInterface;
  21.  
  22. HandleInterface* getInterface() const { return _interface; }
  23. void setInterface(HandleInterface* interface) { assert(!getHandle().isNull()); // should not work if handle is NOT null
  24. _interface = interface; }
  25.  
  26. const Handle& getHandle() const
  27. { return _handle; }
  28.  
  29. protected:
  30.  
  31. typedef Resource<THandle, THandleInterface> Base;
  32.  
  33. Resource(HandleInterface* interface) : _interface(interface) {}
  34.  
  35. Handle _handle;
  36.  
  37. private:
  38.  
  39. HandleInterface* _interface;
  40. };
  41.  
  42. // example:
  43.  
  44. struct Image
  45. { /* ... */ };
  46.  
  47. struct TextureHandle : ResourceHandle
  48. {
  49. unsigned int width, height, depth;
  50. };
  51.  
  52. struct TextureHandleInterface
  53. {
  54. virtual bool load(TextureHandle&, const Image&) = 0;
  55. virtual void destroy(TextureHandle&) = 0;
  56. virtual Image getImageData(const TextureHandle&) const = 0;
  57. };
  58.  
  59. struct Texture : Resource<TextureHandle, TextureHandleInterface>
  60. {
  61. Texture(HandleInterface* interface) : Base(interface) {}
  62.  
  63. bool load(const Image& image) { return getInterface()->load(_handle, image); }
  64. void destroy() { return getInterface()->destroy(_handle); }
  65. Image getImageData() const { return getInterface()->getImageData(_handle); }
  66. };
  67.  
  68. class OglTextureInterface : public TextureHandleInterface
  69. {
  70. public:
  71.  
  72. OglTextureInterface()
  73. {
  74. _nextId = 0;
  75. }
  76.  
  77. virtual bool load(TextureHandle& texture, const Image&)
  78. {
  79. std::cout << "Loading texture: " << &texture;
  80. texture.id = _nextId++;
  81. return true;
  82. }
  83.  
  84. virtual void destroy(TextureHandle& texture)
  85. {
  86. std::cout << "Destroying texture: " << &texture;
  87. }
  88.  
  89. virtual Image getImageData(const TextureHandle&) const
  90. {
  91. return Image();
  92. }
  93.  
  94. private:
  95.  
  96. ResourceHandle::Id _nextId;
  97. };
  98.  
  99. int main(int argc, char* argv[])
  100. {
  101. OglTextureInterface interface;
  102. Texture texture(&interface);
  103.  
  104. texture.load(Image());
  105.  
  106.  
  107. std::cout << "\nTexture ID: " << texture.getHandle().id << '\n';
  108.  
  109. return 0;
  110. }
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
Loading texture: 0xbf9d52cc
Texture ID: 0