fork(2) download
  1. #include <cstddef>
  2.  
  3. #include <iostream>
  4. #include <memory>
  5. #include <type_traits>
  6.  
  7. template <typename, size_t> class FastFunc;
  8.  
  9. template <typename R, typename... Args, size_t Size>
  10. class FastFunc<R(Args...), Size> {
  11. public:
  12. template <typename F>
  13. FastFunc(F f): handler(&Get<F>()) {
  14. new (&storage) F(std::move(f));
  15. }
  16.  
  17. ~FastFunc() {
  18. handler->destroy(&storage);
  19. }
  20.  
  21. R operator()(Args&&... args) {
  22. return handler->apply(&storage, std::forward<Args>(args)...);
  23. }
  24.  
  25. private:
  26. using Storage = typename std::aligned_storage<Size, alignof(max_align_t)>::type;
  27.  
  28. struct Handler {
  29. R (*apply)(void*, Args&&...);
  30. void (*destroy)(void*);
  31. }; // struct Handler
  32.  
  33. template <typename F>
  34. static R Apply(void* f, Args&&... args) {
  35. (*reinterpret_cast<F*>(f))(std::forward<Args>(args)...);
  36. }
  37.  
  38. template <typename F>
  39. static void Destroy(void* f) {
  40. reinterpret_cast<F*>(f)->~F();
  41. }
  42.  
  43. template <typename F>
  44. Handler const& Get() {
  45. static Handler const H = { &Apply<F>, &Destroy<F> };
  46. return H;
  47. } // Get
  48.  
  49. Handler const* handler;
  50. Storage storage;
  51. }; // class FastFunc
  52.  
  53. int main() {
  54. FastFunc<void(), 32> stateless = []() { std::cout << "stateless\n"; };
  55. stateless();
  56.  
  57. bool b = true;
  58. FastFunc<void(), 32> stateful = [&b]() { std::cout << "stateful: " << b << "\n"; };
  59. stateful();
  60.  
  61. b = false;
  62. stateful();
  63.  
  64. return 0;
  65. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
stateless
stateful: 1
stateful: 0