SHARE
TWEET

function_view

ulfben Jan 7th, 2020 65 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
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top