Advertisement
Guest User

Psuedo-Events

a guest
May 22nd, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. // ConsoleApplication8.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5.     #include <string>
  6.     #include <iostream>
  7.     #include <functional>
  8.     #include <vector>
  9.     using namespace std;
  10.  
  11.     template <typename ...Args>
  12.  
  13.     //Simplification for readability
  14.     using delegate = std::function<void(Args...)>;
  15.  
  16.     template <typename ...Args>
  17.     //Signal class -- holds vector of functions.
  18.     class signal {
  19.     private:
  20.         using fn_t = delegate<Args...>;
  21.         std::vector<fn_t> observers;
  22.  
  23.     public:
  24.         void connect(fn_t f) {
  25.             observers.push_back(f);
  26.         }
  27.  
  28.         void disconnect(fn_t f)
  29.         {
  30.             // No code yet.
  31.         }
  32.  
  33.         void operator ()(Args... a) {
  34.             for (auto i : observers)
  35.                 i(a...);
  36.         }
  37.     };
  38.  
  39.     // Button to send Click event through Signal Update.
  40.     struct button {
  41.         signal<int, int> update;
  42.  
  43.         void click(int x, int y) {
  44.             update(x, y);
  45.         }
  46.     };
  47.  
  48.     // Label with PrintNum
  49.     struct label {
  50.         std::string text;
  51.  
  52.         void PrintNum(int x, int y) {
  53.             std::cout <<  x << y << std::endl;
  54.         }
  55.     };
  56.  
  57.     int main() {
  58.         using namespace std::placeholders;
  59.  
  60.         label label1;
  61.         label label2;
  62.  
  63.         button button1;
  64.  
  65.         // Connect buttons, testing two different methods.
  66.         button1.update.connect(std::bind(&label::PrintNum, std::ref(label1), _1, _2));
  67.         button1.update.connect([&](int x, int y) { label1.PrintNum(x, y); });
  68.  
  69.         //Click event, expecting output '23'
  70.         button1.click(2, 3);
  71.  
  72.  
  73.         system("pause");
  74.         return 0;
  75.     };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement