ClassWrapper.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright (C) 2009-present, 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. /// @addtogroup util_other
  9. /// @{
  10. /// A wrapper template to compensate for the fact that some classes get initialized in the constructor but that's not
  11. /// always desirable. One solution is to use a pointer and dynamic allocation but that creates an indirection and it
  12. /// might cause bad cache locality. With this wrapper is scenario is avoided.
  13. template<typename TClass>
  14. class ClassWrapper
  15. {
  16. public:
  17. ClassWrapper()
  18. {
  19. }
  20. /// Call the constructor of the TClass.
  21. template<typename... TArgs>
  22. void construct(TArgs&&... args)
  23. {
  24. ::new(&m_data[0]) TClass(std::forward<TArgs>(args)...);
  25. }
  26. /// Call the destructor of the TClass.
  27. void destroy()
  28. {
  29. reinterpret_cast<TClass*>(&m_data[0])->~TClass();
  30. }
  31. /// Access the instance.
  32. TClass* operator->()
  33. {
  34. return reinterpret_cast<TClass*>(&m_data[0]);
  35. }
  36. /// Access the instance.
  37. const TClass* operator->() const
  38. {
  39. return reinterpret_cast<const TClass*>(&m_data[0]);
  40. }
  41. /// Access the instance.
  42. TClass& operator*()
  43. {
  44. return *reinterpret_cast<TClass*>(&m_data[0]);
  45. }
  46. /// Access the instance.
  47. const TClass& operator*() const
  48. {
  49. return *reinterpret_cast<const TClass*>(&m_data[0]);
  50. }
  51. /// Access the instance.
  52. const TClass* operator&() const
  53. {
  54. return reinterpret_cast<const TClass*>(&m_data[0]);
  55. }
  56. /// Access the instance.
  57. TClass* operator&()
  58. {
  59. return reinterpret_cast<TClass*>(&m_data[0]);
  60. }
  61. /// Access the instance.
  62. TClass* get()
  63. {
  64. return reinterpret_cast<TClass*>(&m_data[0]);
  65. }
  66. /// Access the instance.
  67. const TClass* get() const
  68. {
  69. return reinterpret_cast<const TClass*>(&m_data[0]);
  70. }
  71. private:
  72. /// The data as a POD with correct size and alignment.
  73. alignas(alignof(TClass)) Array<U8, sizeof(TClass)> m_data;
  74. };
  75. /// @}
  76. } // end namespace anki