fork download
  1. #include <iostream>
  2.  
  3. #include <array>
  4. #include <functional>
  5. #include <cstddef>
  6.  
  7. template<std::size_t N>
  8. using intArray = std::array<int, N>;
  9.  
  10. template<std::size_t N>
  11. using callbackType =
  12. std::function<intArray<N>(const intArray<N>&, int)>;
  13.  
  14. template <std::size_t N>
  15. class BaseClass {
  16. public:
  17. virtual intArray<N> CustomBehavior(const intArray<N>& user_array, int user_number) = 0;
  18. protected:
  19. intArray<N> my_array = {0, 0};
  20. };
  21.  
  22.  
  23. template <std::size_t N>
  24. class DerivedClass : public BaseClass<N> {
  25. public:
  26. DerivedClass() = default;
  27.  
  28. DerivedClass(callbackType<N> custom_f)
  29. : customCallback(std::move(custom_f))
  30. {}
  31.  
  32. void SetCustomBehavior(callbackType<N> custom_f) {
  33. customCallback = std::move(custom_f);
  34. }
  35.  
  36. intArray<N> CustomBehavior(const intArray<N>& user_array, int user_number) override {
  37. if (customCallback)
  38. this->my_array = customCallback(user_array, user_number);
  39. return this->my_array;
  40. }
  41.  
  42. private:
  43. callbackType<N> customCallback;
  44. };
  45.  
  46. #include <cassert>
  47.  
  48. static constexpr std::size_t MySize = 2;
  49. using myIntArray = intArray<MySize>;
  50.  
  51. myIntArray my_behavior(const myIntArray& input_array, int a) {
  52. return {a * input_array[0], a * input_array[1]};
  53. }
  54.  
  55. int main() {
  56. myIntArray my_array = {1, 1};
  57.  
  58. // Default constructor
  59. DerivedClass<MySize> foo_1;
  60.  
  61. myIntArray bar_1 = foo_1.CustomBehavior(my_array, 2);
  62. assert(bar_1[0] == 0 && bar_1[1] == 0);
  63.  
  64. // Custom constructor
  65. DerivedClass<MySize> foo_2(my_behavior);
  66. myIntArray bar_2 = foo_2.CustomBehavior(my_array, 2);
  67. assert(bar_2[0] == 2 && bar_2[1] == 2);
  68.  
  69. // Custom behavior set later on
  70. DerivedClass<MySize> foo_3;
  71. foo_3.SetCustomBehavior(my_behavior);
  72. myIntArray bar_3 = foo_3.CustomBehavior(my_array, 2);
  73. assert(bar_3[0] == 2 && bar_3[1] == 2);
  74.  
  75. std::cout << "OK";
  76.  
  77. return 0;
  78. }
Success #stdin #stdout 0s 5652KB
stdin
Standard input is empty
stdout
OK