jack06215

[tutorial] Chain of responsibility pattern

Jul 17th, 2020 (edited)
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <functional>
  4.  
  5. struct Condiment
  6. {
  7.     std::function<std::string()> description;
  8.     std::function<float()> price;
  9. };
  10.  
  11. class Sugar
  12. {
  13. public:
  14.     static std::string description() { return "-Sugar-"; }
  15.     static float price() { return 0.07f; }
  16. };
  17.  
  18. class Milk
  19. {
  20. public:
  21.     static std::string description() { return "-Milk-"; }
  22.     static float price() { return 0.13f; }
  23. };
  24.  
  25. template<typename Call, typename NextCall>
  26. static auto accu(Call call, NextCall next) -> decltype(call() + next())
  27. {
  28.     if (next) return call() + next();
  29.     return call();
  30. }
  31.  
  32.  
  33. int main()
  34. {
  35.     Condiment condiments;
  36.     condiments.description = [=] { return accu(&Milk::description, condiments.description); };
  37.     condiments.description = [=] { return accu(&Sugar::description, condiments.description); };
  38.     condiments.description = [=] { return accu(&Sugar::description, condiments.description); };
  39.  
  40.     condiments.price = [=] { return accu(&Milk::price, condiments.price); };
  41.     condiments.price = [=] { return accu(&Sugar::price, condiments.price); };
  42.     condiments.price = [=] { return accu(&Sugar::price, condiments.price); };
  43.  
  44.     std::cout << "Condiments: " << condiments.description() << '\n';
  45.     std::cout << "Price: " << condiments.price() << '\n';
  46.  
  47.     return 0;
  48. }
Add Comment
Please, Sign In to add comment