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