ulfben

function_view

Jan 7th, 2020
106
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //https://vittorioromeo.info/index/blog/passing_functions_to_functions.html
  2.  
  3. template <typename TSignature>
  4. class function_view;
  5.  
  6. template <typename TReturn, typename... TArgs>
  7. class function_view<TReturn(TArgs...)> final
  8. {
  9. private:
  10.     using signature_type = TReturn(void*, TArgs...);
  11.  
  12.     void* _ptr;
  13.     TReturn (*_erased_fn)(void*, TArgs...);
  14.  
  15. public:
  16.     template <typename T, typename = std::enable_if_t<
  17.                               std::is_callable<T&(TArgs...)>{} &&
  18.                               !std::is_same<std::decay_t<T>, function_view>{}>>
  19.     function_view(T&& x) noexcept : _ptr{(void*)std::addressof(x)}
  20.     {
  21.         _erased_fn = [](void* ptr, TArgs... xs) -> TReturn {
  22.             return (*reinterpret_cast<std::add_pointer_t<T>>(ptr))(
  23.                 std::forward<TArgs>(xs)...);
  24.         };
  25.     }
  26.  
  27.     decltype(auto) operator()(TArgs... xs) const
  28.         noexcept(noexcept(_erased_fn(_ptr, std::forward<TArgs>(xs)...)))
  29.     {
  30.         return _erased_fn(_ptr, std::forward<TArgs>(xs)...);
  31.     }
  32. };
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×