fork download
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. template<typename ReturnType, typename... ParameterTypes>
  5. class FDelegate
  6. {
  7. class FDelegateDummyClass;
  8.  
  9. using MethodType = ReturnType (FDelegateDummyClass::*)(ParameterTypes...);
  10.  
  11. MethodType BoundMethod;
  12.  
  13. public:
  14.  
  15. FDelegate()
  16. : BoundMethod(nullptr)
  17. {
  18. }
  19.  
  20. template<typename ClassName>
  21. void Bind(ReturnType (ClassName::*Method)(ParameterTypes...))
  22. {
  23. BoundMethod = (MethodType&)(Method);
  24. }
  25.  
  26. void Unbind()
  27. {
  28. BoundMethod = nullptr;
  29. }
  30.  
  31. bool IsBound() const
  32. {
  33. return BoundMethod != nullptr;
  34. }
  35.  
  36. template<typename ObjectType>
  37. ReturnType Execute(ObjectType* Object, ParameterTypes... Parameters)
  38. {
  39. return ((FDelegateDummyClass*)Object->*BoundMethod)(Parameters...);
  40. }
  41.  
  42. template<typename ObjectType>
  43. ReturnType ExecuteIfBound(ObjectType* Object, ParameterTypes... Parameters)
  44. {
  45. if (IsBound())
  46. {
  47. return Execute<ObjectType>(Object, Parameters...);
  48. }
  49. }
  50. };
  51.  
  52. class FSampleBase
  53. {
  54. protected:
  55.  
  56. FDelegate<void, int> NotifyFooInvoked;
  57.  
  58. public:
  59.  
  60. void Foo(int Value)
  61. {
  62. NotifyFooInvoked.ExecuteIfBound(this, Value);
  63. }
  64. };
  65.  
  66. class FSampleDerived : public FSampleBase
  67. {
  68. int SampleData;
  69.  
  70. public:
  71.  
  72. FSampleDerived(int Data)
  73. : SampleData(Data)
  74. {
  75. NotifyFooInvoked.Bind(&FSampleDerived::OnFooInvoked);
  76. }
  77.  
  78. void OnFooInvoked(int Value)
  79. {
  80. std::cout << "Foo Invoked: " << Value << " [Sample Data: " << SampleData << "]" << std::endl;
  81. }
  82. };
  83.  
  84. int main()
  85. {
  86. FSampleDerived FirstSample(11);
  87. FSampleDerived* SecondSample = (FSampleDerived*)std::malloc(sizeof(FSampleDerived));
  88.  
  89. std::memcpy(SecondSample, &FirstSample, sizeof(FSampleDerived));
  90.  
  91. FirstSample.Foo(1);
  92. SecondSample->Foo(2);
  93.  
  94. std::free(SecondSample);
  95.  
  96. return 0;
  97. }
Success #stdin #stdout 0s 4344KB
stdin
Standard input is empty
stdout
Foo Invoked: 1 [Sample Data: 11]
Foo Invoked: 2 [Sample Data: 11]