You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

function_hook.h 1.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * \file imperative/src/include/megbrain/imperative/function_hook.h
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. */
  11. #pragma once
  12. #include "megbrain/utils/thin/function.h"
  13. namespace mgb {
  14. namespace imperative {
  15. template <typename TFunction>
  16. class FunctionHook;
  17. template <template <typename> class TFunction, typename TRet, typename... TArgs>
  18. class FunctionHook<TFunction<TRet(TArgs...)>> {
  19. public:
  20. using FunctionType = TFunction<TRet(TArgs...)>;
  21. explicit FunctionHook(FunctionType* fptr) : m_fptr{fptr} { m_backup = *fptr; }
  22. public:
  23. template <
  24. typename THook,
  25. typename = std::enable_if_t<
  26. std::is_invocable_r_v<TRet, THook, FunctionType, TArgs...>, void>>
  27. FunctionHook& apply_hook(THook&& hook) {
  28. // Replace with hooked version
  29. *m_fptr = [func = *m_fptr,
  30. hook = std::forward<THook>(hook)](TArgs... args) -> TRet {
  31. return hook(func, std::forward<TArgs>(args)...);
  32. };
  33. // Convinent for chain call
  34. return *this;
  35. }
  36. private:
  37. FunctionType* m_fptr;
  38. FunctionType m_backup;
  39. public:
  40. ~FunctionHook() { *m_fptr = std::move(m_backup); }
  41. };
  42. template <typename TFunction>
  43. auto make_shared_hook(TFunction* fptr) {
  44. return std::make_shared<FunctionHook<TFunction>>(fptr);
  45. }
  46. } // namespace imperative
  47. } // namespace mgb