emlabcpp
modern opinionated embedded C++ library
function_view.h
Go to the documentation of this file.
1 
24 #pragma once
25 
26 #include "../concepts.h"
27 
28 namespace emlabcpp
29 {
30 
31 template < typename Signature >
33 
34 template < typename ReturnType, typename... ArgTypes >
35 class function_view< ReturnType( ArgTypes... ) >
36 {
37 public:
38  using signature = ReturnType( ArgTypes... );
39 
41  function_view( function_view const& ) = default;
42  function_view( function_view&& ) noexcept = default;
43  function_view& operator=( function_view const& ) = default;
44  function_view& operator=( function_view&& ) noexcept = default;
45 
47  : obj_( reinterpret_cast< void* >( fun ) )
48  , handler_( &FunctionHandler )
49  {
50  }
51 
52  template < std::invocable< ArgTypes... > Callable >
53  function_view( Callable& cb )
54  : obj_( &cb )
55  , handler_( &CallableHandler< Callable > )
56  {
57  }
58 
59  ReturnType operator()( ArgTypes... args ) const
60  {
61  return handler_( obj_, std::forward< ArgTypes >( args )... );
62  }
63 
64 private:
65  template < typename Callable >
66  static ReturnType CallableHandler( void* const ptr, ArgTypes... args )
67  {
68  auto* cb_ptr = reinterpret_cast< Callable* >( ptr );
69  return ( *cb_ptr )( std::forward< ArgTypes >( args )... );
70  }
71 
72  static ReturnType FunctionHandler( void* const ptr, ArgTypes... args )
73  {
74  auto f_ptr = reinterpret_cast< signature* >( ptr );
75  return f_ptr( args... );
76  }
77 
78  using handler = ReturnType( void*, ArgTypes... );
79 
80  void* obj_;
81  handler* handler_;
82 };
83 
84 } // namespace emlabcpp
function_view(function_view const &)=default
ReturnType(ArgTypes...) signature
Definition: function_view.h:38
ReturnType operator()(ArgTypes... args) const
Definition: function_view.h:59
function_view(Callable &cb)
Definition: function_view.h:53
function_view(function_view &&) noexcept=default
MIT License.
Definition: impl.h:31
Args const & args
Definition: min_max.h:83
Definition: function_view.h:32