Advertisement
Guest User

Untitled

a guest
Oct 13th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #include <type_traits>
  2. #include <utility>
  3.  
  4. template<class ReturnType, class...Xs>
  5. struct CallableBase {
  6. virtual ReturnType operator()(Xs...) const = 0;
  7. virtual ReturnType operator()(Xs...) = 0;
  8. virtual void copy(void*) const = 0;
  9. };
  10.  
  11.  
  12.  
  13. template<class F, class ReturnType, class...Xs>
  14. struct Callable final
  15. : CallableBase<ReturnType, Xs...>
  16. {
  17. F f;
  18.  
  19. Callable(F const& f) : f(f) {}
  20.  
  21. virtual void copy(void* memory) const {
  22. new (memory) Callable<F, ReturnType, Xs...>(f);
  23. }
  24.  
  25. virtual ReturnType operator()(Xs... xs) const {
  26. return f(xs...);
  27. }
  28.  
  29. virtual ReturnType operator()(Xs... xs) {
  30. return f(xs...);
  31. }
  32. };
  33.  
  34. template<class F, class ReturnType, class...Xs>
  35. struct CallablePtr final
  36. : CallableBase<ReturnType, Xs...>
  37. {
  38. F *f;
  39.  
  40. CallablePtr(F const* f) : f(f) {}
  41.  
  42. virtual void copy(void* memory) const {
  43. new (memory) CallablePtr<F, ReturnType, Xs...>(f);
  44. }
  45.  
  46. virtual ReturnType operator()(Xs... xs) const {
  47. return f(xs...);
  48. }
  49.  
  50. virtual ReturnType operator()(Xs... xs) {
  51. return f(xs...);
  52. }
  53. };
  54.  
  55.  
  56.  
  57. template<class Signature, unsigned size=128>
  58. class LiteralFn;
  59.  
  60.  
  61. template<class ReturnType, class...Xs, unsigned size>
  62. class LiteralFn<ReturnType(Xs...), size> {
  63. char memory[size];
  64. bool allocated = false;
  65.  
  66. using Base = CallableBase<ReturnType, Xs...>;
  67.  
  68. public:
  69. constexpr LiteralFn(){}
  70.  
  71. template<class F>
  72. constexpr LiteralFn(F const&f) {
  73. if constexpr (std::is_function<F>::value) {
  74. static_assert(sizeof(CallablePtr<F, ReturnType, Xs...>) <= sizeof(memory));
  75. new (memory) CallablePtr<F, ReturnType, Xs...>(f);
  76. } else {
  77. static_assert(sizeof(Callable<F, ReturnType, Xs...>) <= sizeof(memory));
  78. new (memory) Callable<F, ReturnType, Xs...>(f);
  79. }
  80. allocated = true;
  81. }
  82.  
  83. template<class...Ys>
  84. constexpr ReturnType operator()(Ys&&...ys) {
  85. if (allocated) {
  86. return (*reinterpret_cast<Base*>(memory))(std::forward<Ys>(ys)...);
  87. }
  88. return {};
  89. }
  90.  
  91. template<class...Ys>
  92. constexpr ReturnType operator()(Ys&&...ys)const {
  93. if (allocated) {
  94. return *reinterpret_cast<Base*>(memory)(std::forward<Ys>(ys)...);
  95. }
  96. return {};
  97. }
  98. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement