ClassWrapper.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <AnKi/Util/Array.h>
  7. namespace anki
  8. {
  9. /// @addtogroup util_other
  10. /// @{
  11. /// A wrapper template to compensate for the fact that some classes get initialized in the constructor but that's not
  12. /// always desirable. One solution is to use a pointer and dynamic allocation but that creates an indirection and it
  13. /// might cause bad cache locality. With this wrapper is scenario is avoided.
  14. template<typename TClass>
  15. class ClassWrapper
  16. {
  17. public:
  18. ClassWrapper()
  19. {
  20. }
  21. /// Call the constructor of the TClass.
  22. template<typename... TArgs>
  23. void init(TArgs&&... args)
  24. {
  25. ::new(&m_data[0]) TClass(std::forward<TArgs>(args)...);
  26. }
  27. /// Call the destructor of the TClass.
  28. void destroy()
  29. {
  30. reinterpret_cast<TClass*>(&m_data[0])->~TClass();
  31. }
  32. /// Access the instance.
  33. TClass* operator->()
  34. {
  35. return reinterpret_cast<TClass*>(&m_data[0]);
  36. }
  37. /// Access the instance.
  38. const TClass* operator->() const
  39. {
  40. return reinterpret_cast<const TClass*>(&m_data[0]);
  41. }
  42. /// Access the instance.
  43. TClass& operator*()
  44. {
  45. return *reinterpret_cast<TClass*>(&m_data[0]);
  46. }
  47. /// Access the instance.
  48. const TClass& operator*() const
  49. {
  50. return *reinterpret_cast<const TClass*>(&m_data[0]);
  51. }
  52. /// Access the instance.
  53. TClass* get()
  54. {
  55. return reinterpret_cast<TClass*>(&m_data[0]);
  56. }
  57. /// Access the instance.
  58. const TClass* get() const
  59. {
  60. return reinterpret_cast<const TClass*>(&m_data[0]);
  61. }
  62. private:
  63. /// The data as a POD with correct size and alignment.
  64. alignas(alignof(TClass)) Array<U8, sizeof(TClass)> m_data;
  65. };
  66. /// @}
  67. } // end namespace anki