| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- // Callback_18.cpp : Diese Datei enthält die Funktion "main". Hier beginnt und endet die Ausführung des Programms.
- //
- #include <iostream>
- #include <array>
- #include <vector>
- #include <map>
- #include <iostream>
- #include <functional>
- template<class ... Arguments>
- class Callback
- {
- using Function = std::function<void(Arguments ...)>;
- using FunctionPtr = std::shared_ptr<Function>;
- using Functions = std::vector<FunctionPtr>;
- public:
- FunctionPtr addListener(Function f) {
- FunctionPtr fp = std::make_shared<Function>(f);
- _functions.push_back(fp);
- return fp;
- }
- void removeListener(FunctionPtr fp) {
- _functions.erase(std::find(_functions.begin(), _functions.end(), fp));
- }
- void operator()(Arguments ... args) const {
- for (auto& f : _functions)
- f.get()->operator()(args ...);
- }
- private:
- Functions _functions;
- };
- class myClass {
- public:
- static void myFnct(int i) {
- std::cout << "test: " << i<< std::endl;
- };
- };
- void test(int i) {
- std::cout << "test: " << i << std::endl;
- }
- void test2(int i, int j) {
- std::cout << "test: " << i << std::endl;
- return;
- }
- int main()
- {
- Callback<int> callback;
- callback.addListener([&](int i) {
- std::cout << "Listener 1 -> Input is " << i << std::endl;
- });
- auto id = callback.addListener([&](int i) {
- std::cout << "Listener 2 -> Input is " << i << std::endl;
- });
- callback.addListener([&](int i) {
- std::cout << "Listener 3 -> Input is " << i << std::endl;
- });
- callback.addListener(test);
- callback.addListener(&myClass::myFnct);
- callback.removeListener(id);
- callback(71);
- }
|