C++ (Qt)struct ID_ENABLED{};struct ID_COUNT{};... class switch_visitor : public boost::static_visitor<>{public: void operator()(ID_ENABLED) const { // бла-бла-бла } void operator()(ID_COUNT) const { // бла-бла-бла } // и т.д.}; boost::variant<ID_ENABLED, ID_COUNT> id = ID_COUNT(); boost::apply_visitor(switch_visitor(), id);
C++ (Qt)class Window{public: enum id_type { ID_ENABLED, ID_COUNT}; Window() { _map[ID_ENABLED] = &Window::action_enabled; _map[ID_COUNT] = &Window::action_count; } void updateUI() { std::cout << "UbdateUI" << std::endl; } void some_method(id_type id) { _map[id](this); } // <-- Это вместо длинного свитча private: void action_enabled() { std::cout << "ID_ENABLED" << std::endl; updateUI(); } void action_count() { std::cout << "ID_COUNT" << std::endl; } std::map<id_type, std::function<void(Window*)>> _map;}; int main(){ Window wnd; wnd.some_method(Window::ID_COUNT); wnd.some_method(Window::ID_ENABLED); return 0;}
C++ (Qt) _map[ID_ENABLED] = &Window::action_enabled; _map[ID_COUNT] = &Window::action_count; std::map<id_type, std::function<void(Window*)>> _map;
C++ (Qt)typedef int MyClass; class Window{public: enum id_type { ID_ENABLED, ID_COUNT}; Window() { _map[ID_ENABLED] = &Window::action_enabled; _map[ID_COUNT] = &Window::action_count; } void updateUI() { std::cout << "UbdateUI" << std::endl; } void some_method(MyClass & dst, const MyClass & src, id_type id) { _map[id](this, dst, src); } // <-- Вариант свитча с копированием структуры private: void action_enabled(MyClass & dst, const MyClass & src) { std::cout << "ID_ENABLED" << std::endl; dst = src; updateUI(); } void action_count(MyClass & dst, const MyClass & src) { std::cout << "ID_COUNT" << std::endl; dst = src; } std::map<id_type, std::function<void(Window*, MyClass&, const MyClass&)>> _map;}; Window wnd; MyClass src = 1; MyClass dst = 2; wnd.some_method(dst, src, Window::ID_COUNT); wnd.some_method(dst, src, Window::ID_ENABLED);
C++ (Qt)Вариант свитча с копированием структуры private: void action_enabled(MyClass & dst, const MyClass & src) { std::cout << "ID_ENABLED" << std::endl; dst = src; updateUI(); }
C++ (Qt)bool update = false;switch (id) { case ID_ENABLE: ... update = true; break; .... .... update = true;} if (update) { ...}
C++ (Qt)bool update = false;_map[id](this, update); if (update) { ... }