template_tools.h - Engine C API Reference

template_tools.h
  1. #pragma once
  2. #include "assert.h"
  3. namespace stingray_plugin_foundation {
  4. // Convert integer to type.
  5. template <int v>
  6. struct Int2Type { enum {value=v}; };
  7. // Determines if a class is allocator aware.
  8. template <class T>
  9. struct is_allocator_aware {
  10. template <typename C>
  11. static char test_fun(typename C::allocator_aware *);
  12. template <typename C>
  13. static int test_fun(...);
  14. public:
  15. enum {
  16. value = (sizeof(test_fun<T>(0)) == sizeof(char))
  17. };
  18. };
  19. #define IS_ALLOCATOR_AWARE(T) is_allocator_aware<T>::value
  20. #define IS_ALLOCATOR_AWARE_TYPE(T) Int2Type< IS_ALLOCATOR_AWARE(T) >
  21. // Allocator aware constuction
  22. template <class T> inline T &construct(void *p, Allocator &a, Int2Type<true>) {new (p) T(a); return *(T *)p;}
  23. template <class T> inline T &construct(void *p, Allocator &a, Int2Type<false>) {new (p) T; return *(T *)p;}
  24. template <class T> inline T &construct(void *p, Allocator &a) {return construct<T>(p, a, IS_ALLOCATOR_AWARE_TYPE(T)());}
  25. // Helper for casts using a union. This circumvents the aliasing problem that occurs when
  26. // trying to reinterpret a float as int and vice versa for example.
  27. template<typename A, typename B>
  28. A safe_reinterpret_cast(const B &b) {
  29. static_assert(sizeof(A) == sizeof(B), "Types must have same size to be cast");
  30. union U {
  31. A a;
  32. B b;
  33. } u;
  34. u.b = b;
  35. return u.a;
  36. }
  37. }