#include #include #include #include #include template class Callback { using Function = std::function; using FunctionPtr = std::shared_ptr; using Functions = std::vector; public: FunctionPtr addListener(Function f) { FunctionPtr fp = std::make_shared(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; }; void test(int i) { std::cout << "test: " << i << std::endl; } int main() { Callback 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.removeListener(id); callback(71); }