Cuberite
A lightweight, fast and extensible game server for Minecraft
FunctionRef.h
Go to the documentation of this file.
1 
2 #pragma once
3 
4 // Declared only so it can be partially specialized
5 template <class Signature>
7 
35 template <class Ret, class... Args>
36 class cFunctionRef<Ret(Args...)>
37 {
38 public:
40  template <class FunctionObject,
41  typename std::enable_if< // Don't disable the default copy constructor
42  !std::is_same<typename std::decay<FunctionObject>::type, cFunctionRef>::value,
43  int>::type = 0
44  >
45  cFunctionRef(FunctionObject && a_FunctionObject)
46  {
47  // Store an opaque reference to the object.
48  m_CallableData = &a_FunctionObject;
49 
50  // Along with a function that knows how to call the object.
51  m_CallFunction = &ObjectFunctionCaller<FunctionObject>;
52  }
53 
55  Ret operator () (Args... a_Args)
56  {
57  return m_CallFunction(m_CallableData, std::forward<Args>(a_Args)...);
58  }
59 
60 private:
61 
63  template <class ObjectType>
64  static Ret ObjectFunctionCaller(void * a_Callable, Args... a_Args)
65  {
66  // Convert opaque reference to the concrete type.
67  using ObjectPtr = typename std::add_pointer<ObjectType>::type;
68  auto & Object = *static_cast<ObjectPtr>(a_Callable);
69 
70  // Forward the call down to the object.
71  return Object(std::forward<Args>(a_Args)...);
72  }
73 
74  using cCallFunction = Ret(*)(void *, Args...);
75 
78 
81 };
82 
83 
Ret(*)(void *, Args...) cCallFunction
Definition: FunctionRef.h:74
cFunctionRef(FunctionObject &&a_FunctionObject)
Construct from a function object.
Definition: FunctionRef.h:45
static Ret ObjectFunctionCaller(void *a_Callable, Args... a_Args)
Function that performs the call.
Definition: FunctionRef.h:64
cCallFunction m_CallFunction
Function that knows how to call the type erased reference.
Definition: FunctionRef.h:80
void * m_CallableData
Type erased reference to a callable.
Definition: FunctionRef.h:77