capture_fn.h 570 B

123456789101112131415161718192021222324252627282930313233
  1. //
  2. // capture.h
  3. // iterator
  4. //
  5. // Created by Sam Jaffe on 9/23/25.
  6. // Copyright © 2025 Sam Jaffe. All rights reserved.
  7. //
  8. #pragma once
  9. #include <functional>
  10. namespace iterator::detail {
  11. template <typename P, typename T> class CaptureFn {
  12. private:
  13. using R = std::invoke_result_t<P, T>;
  14. private:
  15. P fn_;
  16. void const * key_;
  17. mutable R cache_;
  18. public:
  19. CaptureFn(P fn) : fn_(fn) {} // NOLINT
  20. auto const & operator()(T & arg) const {
  21. if (key_ != &arg) {
  22. new (&cache_) R(std::invoke(fn_, std::forward<T>(arg)));
  23. }
  24. return cache_;
  25. }
  26. };
  27. }